为什么我的另一个列表在从第一个列表复制后被修改

Why is my other list getting modified after copying from the first list

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

最初我用两个 for 循环编写了一个解决方案,然后当我遇到这个问题时,我决定将它变成一个列表理解。我的第二个列表 comper 一直在运行和修改,即使我从 comp

复制了它

我什至打印出 id 并比较对象,python 说它们没有引用同一个对象,但是当我对 comp 执行任何操作时,comper也受到影响。

我知道 python 列表是通过引用传递的,所以如果你想要一个新的副本继续工作,就必须复制它们,但为什么会这样?我不认为这是一个错误因为我已经多次复制列表而没有这种行为

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 但它们仍然不同

Import copy
Comper = copy.deepcopy(comp)