【问题标题】:Why does iteratively generating nested lists not delete the inner list为什么迭代生成嵌套列表不会删除内部列表
【发布时间】:2018-11-09 18:50:53
【问题描述】:
my_list = ['abc', 'def']

outer_list = []
for element in my_list:
    inner_list = []
    for ch in element:
        inner_list.append(ch)
    outer_list.append(inner_list)
print(outer_list)
# output [['a', 'b', 'c'], ['d', 'e', 'f']]

我的问题是,为什么会这样?即,为什么line inner_list = [] 不消除inner_list 的先前实例?我认为这与outer_list 的范围在'for' 块之外有关。也许一旦 inner_list 占据了那里,它就与变量名分离了?这么近吗?

【问题讨论】:

标签: python list scope


【解决方案1】:

当您运行inner_list=[] 时,它只会使变量指向内存中的另一个地址。 outer_list 仍然指向旧的内存地址(之前的 inner_list)。当有指向它的指针时,它不会被释放。

【讨论】:

    【解决方案2】:

    我建议您考虑这两种情况,并在 cmets 中进行完整解释:

    1. list = [] 的情况:

      my1stList = [1, 2 ,3, 4, 5]  # my1stList references  the list [1, 2 ,3, 4, 5]
      my2ndList = my1stList        # my2ndList references the same list as my1stList
      my1stList = []               # my1stList references another list (which is empty)
      print(my2ndList)             # it prints: [1, 2, 3, 4, 5]
      
    2. list[:] = [] 的情况:

      my1stList = [1, 2 ,3, 4, 5]  # my1stList references the list [1, 2 ,3, 4, 5]
      my2ndList = my1stList        # my2ndList references the same list as my1stList
      my1stList[:] = []            # the list referenced by my1stList is emptied
      print(my2ndList)             # it prints: []
      

    我希望您现在可以理解:您附加到outer_list 的每个列表都不会被覆盖。只有它之前的引用 inner_list 发生变化。

    【讨论】:

      猜你喜欢
      • 2012-09-19
      • 2018-06-22
      • 1970-01-01
      • 2013-02-04
      • 2020-07-11
      • 1970-01-01
      • 2011-10-14
      • 1970-01-01
      • 2013-05-11
      相关资源
      最近更新 更多