代码:
num_of_iterations_for_outer_loop = 2
num_of_iterations_for_inner_loop = 3
data = []
for j in range(num_of_iterations_for_outer_loop):
lst2 = []
for k in range(num_of_iterations_for_inner_loop):
lst1 = {}
lst1['1'] = "first_value" # these are not default, in my original code they are coming from some other values after calculation
lst1['2'] = "second_value"
lst1['3'] = "third_value"
lst2.append(lst1)
value = {'values':lst2}
data.append(value)
在外循环中,我必须一次又一次地清除 lst2
列表才能重用它。
在内部循环中,我必须一次又一次地清除 lst1
字典才能重用它。
我知道清除列表的两种方法:
del lst2[:]
lst2 = []
以及一种清除字典的方法:
lst1 = {}
但我不知道这些方法之间的区别以及我应该使用哪一种。
还有其他方法可以清除列表和字典吗?这是更好的方法吗?为什么?
有没有更好的方法来编写整个代码?
最佳答案
以下是每个方法的作用的简要说明:
lst2 = []
实际上没有清除列表的内容。它只是创建一个新的空列表并将其分配给名称lst2
。然后GC的任务就是根据剩余的引用来删除实际的内容。>>> a = [1,2,3] >>> b = a >>> a = [] >>> a [] >>> b [1, 2, 3]
del lst2[:]
就地清除列表内容。>>> a = [1,2,3] >>> b = a >>> del a[:] >>> a [] >>> b []
请注意,另一个列表 b 也会被清除,因为内容已就地删除。
<lst1 = {}
与第 1 点相同。它创建一个空字典并将引用分配给名称lst1
。
就地清除列表的另一种方法是:
lst2[:] = []
关于python - 清除列表和字典的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21696935/