Python:在复制的列表中交换列表元素而不会影响原始列表 [英] Python: swap list elements in a copied list without affecting the original list
本文介绍了Python:在复制的列表中交换列表元素而不会影响原始列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个列表a
和一个列表b
,该列表(应该是)列表a
的副本.
I have a list a
and a list b
which is (should be) a copy of list a
.
a = [[['a'], ['b'], ['c']], [['A'], ['B'], ['C']]]
b = a[:][:]
b[0][1], b[0][2] = b[0][2], b[0][1]
如果我现在查看a
和b
,我将得到以下信息:
If I now look at a
and b
I get the following:
a = [[['a'], ['c'], ['b']], [['A'], ['B'], ['C']]]
b = [[['a'], ['c'], ['b']], [['A'], ['B'], ['C']]]
为什么列表b
中的交换也会影响原始列表a
?
Why does the swap in list b
also affects the original list a
?
谢谢.
推荐答案
b = a[:][:]
只是b = (a[:])[:]
或原始列表副本的副本.原始列表中的列表仍然被引用,并且当您更改它们时,它会显示在两个列表中.
b = a[:][:]
is just b = (a[:])[:]
or a copy of a copy of the original list. The lists inside the original list are still referenced and when you change them it shows in both lists.
你可以做
b = [l[:] for l in a] # a new list, consisting of copies each sublist
或
from copy import deepcopy
b = deepcopy(a)
这篇关于Python:在复制的列表中交换列表元素而不会影响原始列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文