从第一个列表复制后,为什么我的其他列表会被修改

时间:2016-02-11 01:38:24

标签: python list python-3.x reference pass-by-reference

我试图将图表paths格式化为存储为嵌套列表的一系列所有可能路径

最初我用两个for循环编写了一个解决方案,然后当我遇到这个问题时,我决定将它变成一个列表理解。即使我从comper

复制,我的第二个列表comp也会继续进行操作和修改

我甚至打印出id并比较了对象,python说他们没有引用相同的对象,但是当我在comp上执行任何操作时,comper也受到了影响。

我知道python列表是通过引用传递的,所以如果你想要一个全新的副本可以复制它们,但为什么会这样呢?我不认为它是一个bug,因为它是一个bug我没有这种行为就已经多次复制了列表

paths = {
         'A': ['B', 'C'],
         'B': ['D'],
         'C': ['E']
         }

comp = [[key, i] for key in sorted(paths, key = None) for i in paths.get(key) if isinstance(paths.get(key), list)]
print(comp, 'this is the original comp')

comper = comp[:] # tried to copy the contents of comp into comper even tried list(comp), still get the same result
print(comper, 'comper copied, is unchanged')

if comp is comper:
    print('yes')
else:
    print(id(comp), id(comper))

for count, ele in enumerate(comp):
    for other in comp:
        if ele[-1] == other[0]:
            comp[count].append(other[-1])
            comp.remove(other)
            # comper.remove(other) fixes the problem but why is comper getting modified even when id's are different       

print(comper, 'apparently comper has changed because the operation was carried out on both')
print(comp)

print(id(comp), id(comper))

这是我得到的输出

[['A', 'B'], ['A', 'C'], ['B', 'D'], ['C', 'E']] this is the original comp
[['A', 'B'], ['A', 'C'], ['B', 'D'], ['C', 'E']] comper copied, is unchanged
139810664953992 139810664953288
[['A', 'B', 'D'], ['A', 'C', 'E'], ['B', 'D'], ['C', 'E']] apparently comper has changed because the operation was carried out on both
[['A', 'B', 'D'], ['A', 'C', 'E']]
139810664953992 139810664953288

comper有额外的元素,因为它们没有从列表中删除,如果我取消注释从comper删除其他列表的行,那么我基本上得到相同的结果

我甚至打印出了底部的id,他们仍然不同

1 个答案:

答案 0 :(得分:0)

Import copy
Comper = copy.deepcopy(comp)