【发布时间】:2020-06-17 04:37:12
【问题描述】:
假设我正在对数组执行一些操作,如下所示:
>>arr = np.array([1,2,34,567,433243,787,832])
>>h = np.where(arr < 100, {'hello' : 1}, {'hi' : 2 })
array([{'hello': 1}, {'hello': 1}, {'hello': 1}, {'hi': 2}, {'hi': 2},{'hi': 2}, {'hi': 2}], dtype=object)
当我尝试在某些选择性索引处添加键值对时,它会在所有索引中复制并给我这样的结果:
>>h[0]['hola']=12
>>h[4]['heyy']=11
>>h
array([{'hello': 1, 'hola': 12}, {'hello': 1, 'hola': 12},{'hello': 1, 'hola': 12}, {'hi': 2, 'heyy': 11},{'hi': 2, 'heyy': 11}, {'hi': 2, 'heyy': 11},{'hi': 2, 'heyy': 11}], dtype=object)
虽然我希望这些值仅在那些特定的索引(0 和 4)处发生变化并得到如下结果:
array([{'hello': 1, 'hola': 12}, {'hello': 1}, {'hello': 1}, {'hi': 2}, {'hi': 2, 'heyy': 11}, {'hi': 2,}, {'hi': 2}], dtype=object)
如何获得所需的输出?提前致谢
【问题讨论】:
-
您创建了两个 dict 项目,然后拥有它们的多个副本。因此,更改一个将更改所有副本。如果您使用
[id(d) for d in h]打印数组中每个字典的ID[72361176, 72361176, 72361176, 75001400, 75001400, 75001400, 75001400],您可以看到这一点,您可以看到前3 个字典实际上都是同一个字典,最后4 个字典都是同一个字典 -
好的,知道了。但是我如何让它们指向不同的内存位置,以便它们被视为唯一
-
是否需要使用numpy.where?您可以通过列表理解获得相同的结果
h = np.array([{'hello': 1} if i < 100 else {'hi': 2} for i in arr]) -
哦,是的..非常感谢@ChrisDoyle
-
我不认为从字典列表中创建一个数组有任何优势。做任何事情都必须迭代,列表迭代更快。
标签: python python-3.x numpy dictionary