我创建了一个名为 matrix 的字典,其中包含0到3的键,然后这些值是名称列表。每个键具有相同的值(名称列表)。当我为一个名称分配节点时,我想更新字典以仅从一个键中删除该名称。如下面的代码所示,如果我想通过删除值" jason"来更新键0,它删除了" jason"从所有其他键也。我仍然需要" jason"仅在从键0中删除键1到3的值。
node = [0,1,2,3]
names = ["jason", "martin", "ronnie", "mike"]
def table (node, names):
options = {}
for i in range(len(node)):
options [i] = names
return options
matrix = table(node,names)
print "Before removing Jason: " + str(matrix)
alist = matrix[0]
alist.remove('jason')
matrix[0] = alist
print "After removing Jason: " + str(matrix)
print matrix
我还附上了截图:
答案 0 :(得分:3)
词典中的所有键都指向相同的列表。您想要的是将该列表的副本分配给每个键,以便可以单独修改副本。替换此代码:
for i in range(len(node)):
options [i] = names
与
for i in range(len(node)):
options [i] = names[:]
答案 1 :(得分:1)
列表是python中的引用,意思是:
>>> a = [1, 2, 3]
>>> b = a
>>> a is b
True
>>> a[0] = 4
>>> b
[4, 2, 3]
如果要创建新列表,则必须执行以下操作:
options [i] = list(names)
答案 2 :(得分:0)
解决方案:而不是分配names
分配names[:]
,因为您每次都分配相同的引用。
names[:]
(因为names
是标准列表)会创建names
的副本,因为您正在切割所有内容。
答案 3 :(得分:0)
您要做的是创建一个新数组,而不是修改数组。
node = [0,1,2,3]
names = ["jason", "martin", "ronnie", "mike"]
def table (node, names):
options = {}
for i in range(len(node)):
options [i] = names
return options
matrix = table(node,names)
print "Before removing Jason: " + str(matrix)
matrix[0] = [x for x in alist where x is not 'jason']
print "After removing Jason: " + str(matrix)
print matrix