python - 清除列表和字典的最佳方法

标签 python python-2.7 dictionary

代码:

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 字典才能重用它。

我知道清除列表的两种方法:

  1. del lst2[:]

  2. lst2 = []

以及一种清除字典的方法:

  1. lst1 = {}

但我不知道这些方法之间的区别以及我应该使用哪一种。

还有其他方法可以清除列表和字典吗?这是更好的方法吗?为什么?

有没有更好的方法来编写整个代码?

最佳答案

以下是每个方法的作用的简要说明:

  1. lst2 = []实际上没有清除列表的内容。它只是创建一个新的空列表并将其分配给名称lst2。然后GC的任务就是根据剩余的引用来删除实际的内容。

    >>> a = [1,2,3]
    >>> b = a
    >>> a = []
    >>> a
    []
    >>> b
    [1, 2, 3]
    
  2. del lst2[:] 就地清除列表内容。

    >>> a = [1,2,3]
    >>> b = a
    >>> del a[:]
    >>> a
    []
    >>> b
    []
    

    请注意,另一个列表 b 也会被清除,因为内容已就地删除。

  3. lst1 = {} 与第 1 点相同。它创建一个空字典并将引用分配给名称 lst1

    <

就地清除列表的另一种方法是:

lst2[:] = []

关于python - 清除列表和字典的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21696935/

相关文章:

python - 从 python 3 中的字符串中删除 unicode 表示的最简单方法?

python - 更改图上的背景图像

linux - 如何告诉 rpm 查看特定目录的依赖项?

c# - 从字典 C# 中查找特定键

python - 如何仅将行从一个数据帧移动到第二个数据帧中不存在 ID 的另一个数据帧?

Python:创建列表列表作为字典值

Python注解箭头方向

python - 打印功能打印最近耗时的东西

python - 在字典中按其键值重复每个成员而不使用 np.repeat?

arrays - 在 Swift 中将字符串缩减为字典