交换时每次迭代后的python list.clear()函数为空列表



我正在尝试在列表中添加数据。我使用了一个临时列表,将其数据交换到另一个列表b,然后在每次迭代中清除其数据当使用temp.clear((时,我的最终输出为空。但当使用temp=[]时,我得到了正确的输出。

请说明为什么在使用temp.clear((和temp=[]时会有不同的输出。

a=['apple','pizza','veg','chicken','cheese','salad','chips','veg']
b=[]
temp=[]
for i in range(len(a)):
temp.append(a[i])
b.append(temp)
temp.clear()
#temp = []
print(b)        

输出

#temp.clear()
[[], [], [], [], [], [], [], []]
#temp = []
[['apple'], ['pizza'], ['veg'], ['chicken'], ['cheese'], ['salad'], ['chips'], ['veg']]

temp.clear()从列表中删除所有项目(请参阅文档(。temp = []不清除任何列表。相反,它会创建一个新的空列表。由于将temp附加到b,因此使用temp = []时这些值将保持不变,但使用temp.clear()时会清除这些值。

最新更新