Python:如何正确地将列表值附加到列表中?

3

我想将temp列表的值添加到主列表中。我尝试将一些值添加到temp列表中,然后将temp列表附加到主列表中,如下所示,但主列表总是显示最新的值。

>>> temp =[]
>>> temp.append(123)
>>> temp.append(10)
>>> temp.append(18)
>>> mutR =[]
>>> mutR.append(temp)
>>> print mutR
[[123, 10, 18]]
>>> temp[:]=[]
>>> temp.append(3)
>>> temp.append(4)
>>> temp.append(5)
>>> mutR.append(temp)
>>> print mutR
[[3, 4, 5], [3, 4, 5]]

我的期望是:

>>> print mutR
[[123, 10, 18], [3, 4, 5]] 

但它是[[3, 4, 5], [3, 4, 5]]

7个回答

2

这个陈述

temp[:] = []

该代码从temp中删除所有元素,您想要做的是

temp = []

这将创建一个新的空列表并将其引用存储到temp中。

在您的代码中,只有一个列表对象,它被添加两次到mutR,如果您添加例如

temp.append(99)
print mutR

如果你将以下代码添加到你的原始代码中,你会看到答案是[[3, 4, 5, 99], [3, 4, 5, 99]]


1
问题在于当你将 temp 添加到 mutR 中时,mutR 只包含对 temp引用。无论对 temp 进行了什么更改,mutR中的 temp 也会相应地发生更改。因此,解决方法是使用复制
>>> temp =[]
>>> temp.append(123)
>>> temp.append(10)
>>> temp.append(18)
>>> mutR =[]
>>> import copy
>>> mutR.append(copy.copy(temp))
>>> print mutR
[[123, 10, 18]]
>>> temp[:]=[]
>>> temp.append(3)
>>> temp.append(4)
>>> temp.append(5)
>>> mutR.append(temp)
>>> print mutR
[[123, 10, 18], [3, 4, 5]]

1

这里是你要的内容

>>> temp =[]
>>> temp.append(123)
>>> temp.append(10)
>>> temp.append(18) 
>>> mutR =[temp]
>>> print(mutR)
[[123, 10, 18]]
>>>
>>>
>>> temp=[]
>>> temp.append(3)
>>> temp.append(4)
>>> temp.append(5)
>>> mutR.append(temp)
>>> print(mutR)
[[123, 10, 18], [3, 4, 5]]

0
你正在寻找 extend 方法。
>>> l = [1, 2, 3]
>>> l.extend([4, 5, 6])
>>> print l
[1, 2, 3, 4, 5, 6]

这有所帮助,但我想保留方括号,就像这样[[1,2,3],[4,5,6]]。我想这样使用它:l[0](=[1,2,3]),l[1](=[4,5,6]) - Sang Lee

0

mutR.append(temp)temp 添加到 mutR 中,temp[:]=[] 使 temp 再次成为空列表,因为 mutR 中的 temp 是对 temp引用而不是副本,所以它也变成了一个空列表。

然后你向空的 temp 添加了三个元素,并使用 mutR.append(temp) 将其添加到 mutR 中,这样你的列表中就有两个对 temp引用

最好一开始就使用 mutR.append(temp[:]) # <- copy of temp not a reference 来添加 temp 的副本到 mutR 中,这样后来对 temp 的更改就不会影响它。

In [6]: mutR.append(temp[:])   # copy temp  
In [7]: temp[:]=[]    
In [8]: temp.append(3)    
In [9]:  temp.append(4)    
In [10]: temp.append(5)    
In [11]: mutR.append(temp)    
In [12]: mutR
Out[12]: [[123, 10, 18], [3, 4, 5]]

我更喜欢显式调用 copy.copycopy.deepcopy 来创建新对象,而不是使用切片。 - Adam Smith
@AdamSmith,这取决于个人喜好,在处理单个列表时并不是必需的。 - Padraic Cunningham

0
在Python中,除非明确表示要进行复制,否则几乎不会进行复制。特别是,append不会进行复制;您附加的对象所做的任何更改都将反映在列表中,因为该列表保存对原始对象的引用。
为避免出现此类问题,请不要在想要新对象时清除现有对象。相反,请创建一个新对象:
temp = []

替代

temp[:] = []

我想,如果你真的想清除原始的temp列表而不是替换它,你可以在添加时先制作一个副本:

mutR.append(temp[:])

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接