我试图将图表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
删除其他列表的行,那么我基本上得到相同的结果
答案 0 :(得分:0)
Import copy
Comper = copy.deepcopy(comp)