【问题标题】:How to use dictionary to replace the items in the inner list of a list?如何使用字典替换列表内部列表中的项目?
【发布时间】:2018-03-28 17:26:53
【问题描述】:

如何使用字典替换列表内部列表中的项目?

这很好用

import numpy as np
ss_dict = {
        1 : np.array([1,0,0,0,0,0]),
        2 : np.array([0,1,0,0,0,0]),
        3 : np.array([0,0,1,0,0,0]),
        4 : np.array([0,0,0,1,0,0]),
        5 : np.array([0,0,0,0,1,0]),
        6 : np.array([0,0,0,0,0,1]),
    }

l=np.array([1,2,3])
l = np.array([ss_dict[i] for i in l])
print(l)

输出:

[[1 0 0 0 0 0]
 [0 1 0 0 0 0]
 [0 0 1 0 0 0]]

但这有错误TypeError: unhashable type: 'numpy.ndarray'

l=np.array([[1,2,3],[4,5,6]])
l = np.array([ss_dict[i] for i in (j for j in l)])
print(l)

我要输出:

[
[[1 0 0 0 0 0]
 [0 1 0 0 0 0]
 [0 0 1 0 0 0]]

 [[0 0 0 1 0 0]
 [0 0 0 0 1 0]
 [0 0 0 0 0 1]]
 ]

【问题讨论】:

  • for i in (j for j in l) 只是for i in l。您是否要扁平化l,即相当于for i in [1,2,3,4,5,6]?
  • 我已经更新了问题,现在可以了吗?如果可能的话,您能否删除反对票?谢谢! @AlexHall
  • @lanselibai,当然 - 查看更新的答案。

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


【解决方案1】:

这应该会有所帮助。您只需要在列表推导中创建一个列表推导即可。

res = np.array([[ss_dict[j] for j in i] for i in l])

结果:

[[[1 0 0 0 0 0]
  [0 1 0 0 0 0]
  [0 0 1 0 0 0]]

 [[0 0 0 1 0 0]
  [0 0 0 0 1 0]
  [0 0 0 0 0 1]]]

【讨论】:

  • 我现在更新了这个问题。基本上,我希望将每个数字替换为字典中的值。
猜你喜欢
  • 1970-01-01
  • 2021-10-14
  • 2016-09-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-09
  • 1970-01-01
相关资源
最近更新 更多