Nad*_*der 2 python dictionary list
我在Python Dictionary中看到一些不寻常的行为:
import numpy as np
td =[np.Inf, 2, 3]
a = {}
# First initialize contents of dictionary to a list of values
for k in range(10):
a[k] = td
#now I want to access the contents to modify them based on certain criteria
for k in range(10):
c = a[k]
c[0] = k
a[k] = c
Run Code Online (Sandbox Code Playgroud)
从这里我可以预期每个字典键值的列表中的每个第一项都会根据(c [0] = k)进行更改,但是,我最后得到的是字典的所有值都更新到最后k的值:如
{0: [9, 2, 3], 1: [9, 2, 3], 2: [9, 2, 3], 3: [9, 2, 3],
4: [9, 2, 3], 5: [9, 2, 3], 6: [9, 2, 3], 7: [9, 2, 3],
8: [9, 2, 3], 9: [9, 2, 3]}
Run Code Online (Sandbox Code Playgroud)
我错过了什么,或者字典定义中有什么问题?我可以以不同的方式解决这个问题,以便我的代码能够运行,但我对字典类的行为方式感兴趣.
因为每个键都获得相同的列表 ...要创建列表的浅表副本,请使用以下语法:
for k in range(10):
a[k] = td[:]
Run Code Online (Sandbox Code Playgroud)
演示:
>>> d = {}
>>> el = [1, 2, 3]
>>> d[0] = el
>>> d[1] = el
>>> map(id, d.values())
[28358416, 28358416]
Run Code Online (Sandbox Code Playgroud)