Python列表遍历和更新

时间:2018-09-20 14:51:27

标签: python traversal nested-lists

我正在尝试更改z list的list元素的最后一个索引处的元素,但是出现错误

l=['n1','n2','n3','n4']
path=['x','n1','y','z','n2']
y = ['n']
path+= y
d=0
seen = set()
for i in l:
   if i in path:
     f=0
   else:
      d+=1
      seen.add(i)


n=0
z = [[]]*d
for i in seen:
   z[n] = path
   z[n][-1] = i
   n+=1
print(z)

z应该是

[['x', 'n1', 'y', 'z', 'n2', 'n3'], ['x', 'n1', 'y', 'z', 'n2', 'n4']] 

,但其给出的列表元素的最后索引仅为n3,即

 [['x', 'n1', 'y', 'z', 'n2', 'n3'], ['x', 'n1', 'y', 'z', 'n2', 'n3']] 

我无法弄清楚为什么它没有给出正确的结果。

2 个答案:

答案 0 :(得分:4)

您在每次迭代中都将path的引用分配给z[n],并更改列表的最后一个元素,因此不仅z[n]会更改,而且path得到改变。您应该将path的副本分配给z[n]

更改:

z[n] = path

收件人:

z[n] = path[:]

答案 1 :(得分:1)

这可以一行完成:

z = [path +[i] for i in l if i not in path]
(xenial)vash@localhost:~/python/stack_overflow$ python3.7 helping.py 
[['x', 'n1', 'y', 'z', 'n2', 'n3'], ['x', 'n1', 'y', 'z', 'n2', 'n4']]