【问题标题】:Dynamically appending one list into another动态地将一个列表附加到另一个列表中
【发布时间】:2022-10-25 05:47:05
【问题描述】:

我在python中有以下非常简单的实现

 m = []
 l = []
 l.append('A')
 l.append('B')
 l.append('C')
 m.append(l)
 l.clear()
 print(m) --> this gives empty list.

我试过了

 m = []
 l = []
 n = []
 l.append('A')
 l.append('B')
 l.append('C')
 n = l
 m.append(n)
 l.clear()
 print(m) --> this gives empty list too

但是当我不清除 l 时,print(m) 会给我想要的列表,即 ['A','B','C']。为什么当我清除列表 l 时 python 会清除列表 m。它们是两个独立的变量?

【问题讨论】:

    标签: python list


    【解决方案1】:

    当您将一个列表传递给另一个列表时,它会在那里引用它 因此,当您清除该列表时,您的原始列表元素也会被清除 尝试这个

    m = []
    l = []
    l.append('A')
    l.append('B')
    l.append('C')
    m.append(l.copy())  -> use list.copy()
    l.clear()
    print(m) 
    

    【讨论】:

    • 我正在做的是“少知识是危险的”的完美例子。
    【解决方案2】:

    两个变量都是指向同一个对象的引用。要创建一个新列表,您需要使用 n = l[:]

    【讨论】:

      【解决方案3】:

      list.copy 的替代方案:

      m.append(l[:])
      

      或者

      m.append(list(l))
      

      将附加到m 一个“新”创建的列表。

      在某些情况下,对象的deep copy 也可能是正确的解决方案:

      from copy import deepcopy
      ...
      m.append(deepcopy(l))
      ...
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-03-17
        • 2018-01-13
        • 1970-01-01
        • 2023-03-26
        • 1970-01-01
        • 1970-01-01
        • 2015-07-11
        相关资源
        最近更新 更多