Python:将列表追加到另一个列表并清除第一个列表 [英] Python: Append a list to another list and Clear the first list
问题描述
所以这真让我震惊.我正在处理一个python代码,在其中创建一个列表,将其添加到主列表中,然后清除第一个列表以向其中添加更多元素.当我清除第一个列表时,甚至主列表也会被清除.我做了很多列表附加和清除操作,但从未观察到.
So this just blew my mind. I am working on a python code where I create a list, append it to a master list and clear the first list to add some more elements to it. When I clear the first list, even the master list gets cleared. I worked on a lot of list appends and clears but never observed this.
list1 = []
list2 = []
list1 = [1,2,3]
list2.append(list1)
list1
[1, 2, 3]
list2
[[1, 2, 3]]
del list1[:]
list1
[]
list2
[[]]
我知道添加字典会发生这种情况,但是我不知道如何处理列表.可以请人详细说明吗?
I know this happens with appending dictionaries but I did not know how to deal with lists. Can some one please elaborate?
我正在使用Python2.7
I am using Python2.7
推荐答案
将list
传递给append
之类的方法只是将 reference 传递给由引用的同一list
list1
,所以这就是附加到list2
的内容.它们仍然是相同的list
,只是从两个不同的地方引用.
Passing a list
to a method like append
is just passing a reference to the same list
referred to by list1
, so that's what gets appended to list2
. They're still the same list
, just referenced from two different places.
如果您想打断它们之间的纽带,请执行以下任一操作:
If you want to cut the tie between them, either:
- 插入
list1
的副本,而不是list1
本身的副本,例如list2.append(list1[:])
或 -
append
清除后,用新的list
替换list1
,而不是进行清除,将del list1[:]
更改为list1 = []
- Insert a copy of
list1
, notlist1
itself, e.g.list2.append(list1[:])
, or - Replace
list1
with a freshlist
afterappend
ing instead of clearing in place, changingdel list1[:]
tolist1 = []
注意:尚不清楚,但是如果您想将list1
的内容添加到list2
(因此,list2
应该变成[1, 2, 3]
而不是[[1, 2, 3]]
嵌套list
中的值),您想调用list2.extend(list1)
,而不是append
,在这种情况下,不需要浅表副本;那时来自list1
的值将被单独地append
设置,并且list1
和list2
之间将不再存在联系(因为值是不可变的int
s;如果它们是可变的,例如嵌套的) list
,dict
等,您需要复制它们以完全切断领带,例如使用
Note: It's a little unclear, but if you want the contents of list1
to be added to list2
(so list2
should become [1, 2, 3]
not [[1, 2, 3]]
with the values in the nested list
), you'd want to call list2.extend(list1)
, not append
, and in that case, no shallow copies are needed; the values from list1
at that time would be individually append
ed, and no further tie would exist between list1
and list2
(since the values are immutable int
s; if they were mutable, say, nested list
s, dict
s, etc., you'd need to copy them to completely sever the tie, e.g. with copy.deepcopy
for complex nested structure).
这篇关于Python:将列表追加到另一个列表并清除第一个列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!