Python:将列表追加到另一个列表并清除第一个列表 [英] Python: Append a list to another list and Clear the first list

查看:172
本文介绍了Python:将列表追加到另一个列表并清除第一个列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以这真让我震惊.我正在处理一个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:

  1. 插入list1的副本,而不是list1本身的副本,例如list2.append(list1[:])
  2. append清除后,用新的list替换list1,而不是进行清除,将del list1[:]更改为list1 = []
  1. Insert a copy of list1, not list1 itself, e.g. list2.append(list1[:]), or
  2. Replace list1 with a fresh list after appending instead of clearing in place, changing del list1[:] to list1 = []

注意:尚不清楚,但是如果您想将list1内容添加到list2(因此,list2应该变成[1, 2, 3]而不是[[1, 2, 3]]嵌套list中的值),您想调用list2.extend(list1),而不是append,在这种情况下,不需要浅表副本;那时来自list1的值将被单独地append设置,并且list1list2之间将不再存在联系(因为值是不可变的int s;如果它们是可变的,例如嵌套的) listdict等,您需要复制它们以完全切断领带,例如使用

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 appended, and no further tie would exist between list1 and list2 (since the values are immutable ints; if they were mutable, say, nested lists, dicts, etc., you'd need to copy them to completely sever the tie, e.g. with copy.deepcopy for complex nested structure).

这篇关于Python:将列表追加到另一个列表并清除第一个列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆