【问题标题】:Replace elements in 2D list with corresponding value in dictionary?用字典中的相应值替换二维列表中的元素?
【发布时间】:2016-05-06 14:55:05
【问题描述】:

我有一个 2D Python 列表。我也有一本字典。我想生成一个与列表形状相同的numpy矩阵,其中列表中的每个元素都替换为字典中的相应值。

例如,这是我的 Python 列表:

[[约翰玛丽]

[吉姆·简]]

例如,我希望创建这个(一个 numpy 矩阵,而不是 2D Python 列表):

[[85 53]

[76 45]]

从字典中检索值的位置。

最快的方法是什么?我需要它非常快。

【问题讨论】:

    标签: python list python-3.x numpy dictionary


    【解决方案1】:

    您可以将一个函数应用于整个 numpy 数组:

    >>> pylist = [['John','Mary'],['Jim', 'Jane']]
    >>> nparray = np.asarray(pylist)
    >>> print nparray
    [['John' 'Mary']
     ['Jim' 'Jane']]
    >>> dt = {'John':86, 'Mary':53, 'Jim':76, 'Jane':45}
    >>> func = np.vectorize(lambda x: dt[x])
    >>> print func(nparray)
    [[86 53]
     [76 45]]
    

    【讨论】:

      猜你喜欢
      • 2011-05-06
      • 2021-12-12
      • 2017-01-11
      • 2023-04-07
      • 1970-01-01
      • 1970-01-01
      • 2021-06-15
      • 1970-01-01
      • 2021-09-18
      相关资源
      最近更新 更多