首页 > 解决方案 > 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']]

标签: pythonpython-3.xlist

解决方案


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


推荐阅读