为什么这段代码会改变两个列表(id不一样)?

时间:2015-07-02 11:13:34

标签: python list

我有这些清单:

l1 = [['a2', 1], ['a2', 2], ['a2', 3], ['a2', 4], ['a2', 5]]
membership = [0, 1, 1, 2, 3]

我做:

l2 = l1[:]
[item.append(membership[i]) for i, item in enumerate(l2)]

但两个列表现在看起来像:

[['a2', 1, 0], ['a2', 2, 1], ['a2', 3, 1], ['a2', 4, 2], ['a2', 5, 3]]

我以为l1[:]会返回副本吗? l2 = list(l1)

的行为相同
id(l2) == id(l1)

返回

False

1 个答案:

答案 0 :(得分:4)

l1[:]只需创建l1的浅表副本,但它不适用于嵌套列表。对于嵌套列表,您需要copy.deepcopy

>>> import copy
>>> l1 = [['a2', 1], ['a2', 2], ['a2', 3], ['a2', 4], ['a2', 5]]
>>> membership = [0, 1, 1, 2, 3]
>>> l2=copy.deepcopy(l1)
>>> [item.append(membership[i]) for i, item in enumerate(l2)]
[None, None, None, None, None]
>>> l1
[['a2', 1], ['a2', 2], ['a2', 3], ['a2', 4], ['a2', 5]]
>>> l2
[['a2', 1, 0], ['a2', 2, 1], ['a2', 3, 1], ['a2', 4, 2], ['a2', 5, 3]]
>>> 

注意:更改列表推导中的列表不是正确的方法。而是使用正常的for循环。

for i, item in enumerate(l2):
    item.append(membership[i])