我正在尝试使用附加函数将列表附加到列表。请参阅下面的代码 - temp 将是动态创建的临时列表。我想将 temp 附加到 list1。
temp = []
list1 = []
for num in range(0,2):
temp.clear()
temp.append(num)
list1.append(temp)
print(list1)
list1 中的预期输出是 [[0],[1]]。但是我得到[[1],[1]]。 有人可以解释一下这背后的原因吗?追加应追加到列表而不更改列表。
最佳答案
由于您已附加整个 temp
列表,因此 list1
包含对该列表的引用。因此,当您使用 temp.clear()
和 temp.append(num)
修改 temp
时,list1 也会被修改。如果您不希望发生这种情况,则需要附加一份副本:
import copy
temp = []
list1 = []
for num in range(0,2):
temp.clear()
temp.append(num)
list1.append(copy.copy(temp))
print(list1)
> [[0]]
> [[0], [1]]
获得所需结果的另一种方法是使用 temp = []
而不是 temp.clear()
。这将使 temp
指向内存中的一个新对象,而使 list1
中引用的对象保持不变。两者都有效!
关于Python 追加函数未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62226594/