[python list.clear()交换时每次迭代后的功能为空列表

问题描述 投票:0回答:1

我正在尝试在列表中添加数据。我使用了一个临时列表,将其数据交换到另一个列表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']]
python python-3.x list
1个回答
0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.