原始程序
import numpy as np
dict = {0:'a',1:'b',3:'c'}
index = np.array([0,1])
out = dict[index]
print(out)
出现错误
TypeError: unhashable type: 'numpy.ndarray'
出错原因
不能用数组来索引字典。
修改后的程序
import numpy as np
dict = {0:'a',1:'b',3:'c'}
index = np.array([0,1])
out = [dict[i] for i in index]
print(out)
# 输出结果:
['a', 'b']
本文介绍了一种常见的Python编程错误——使用NumPy数组索引字典时导致的TypeError,并提供了解决方案,通过列表推导式正确获取字典中对应值。

938

被折叠的 条评论
为什么被折叠?



