Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/xpath/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python附加函数未按预期工作_Python - Fatal编程技术网

Python附加函数未按预期工作

Python附加函数未按预期工作,python,Python,我试图使用append函数将列表附加到列表中。请参阅下面的代码-临时列表是动态创建的。我想将temp附加到列表1 temp = [] list1 = [] for num in range(0,2): temp.clear() temp.append(num) list1.append(temp) print(list1) 列表1中预期的输出为[[0],[1]]。但是我得到了[[1],[1]]。 有人能解释这背后的原因吗。Append应该在不更改列表的情况下追加

我试图使用append函数将列表附加到列表中。请参阅下面的代码-临时列表是动态创建的。我想将temp附加到列表1

temp = []
list1 = []
for num in range(0,2):
    temp.clear()
    temp.append(num)
    list1.append(temp)
    print(list1)
列表1中预期的输出为[[0],[1]]。但是我得到了[[1],[1]]。
有人能解释这背后的原因吗。Append应该在不更改列表的情况下追加到列表。

由于您已追加了整个
temp
列表,因此
list1
包含对该列表的引用。因此,当您使用
temp.clear()
temp.append(num)
修改
temp
时,列表1也会被修改。如果不希望发生这种情况,则需要附加一份副本:

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
中引用的对象保持不变。两个都有用

这回答了你的问题吗?问题是每次循环重新运行时,你都要用
temp.clear()
清除它。尝试删除它您可以跳过
copy
模块,只使用规范的浅拷贝切片:
list1.append(temp[:])
或(从3.3开始)
list1.append(temp.copy())
。如果
列表
中包含可变对象,那么您只需要使用
复制
模块,在这种情况下,您可以使用
copy.deepcopy
。您是否阅读了我在代码下面的第二个答案?它也不使用
copy
。很多方法,谢谢你!是的,我有。只是指出他们两个都不需要。就个人而言,我支持您的第二种解决方案(重新绑定新的
列表
),因为它更简单,而且可能更快。