【问题标题】:How to avoid memory referencing to lists in python during continuous concatenation? [duplicate]如何在连续连接期间避免内存引用python中的列表? [复制]
【发布时间】:2019-06-20 10:07:05
【问题描述】:

我的要求是,我想要一个最终列表作为输出

在与其他列表连接期间参与循环(我作为其他一些计算的输出得到),但在下面

由于内存引用,实现它无法正常工作,我该如何避免这种情况。 在 Python 中

请原谅我的语法

test_list=[[0,1],[2,3]]
result_list=[]
for i in range(3):
  result_list=list(result_list)+list(test_list)
  test_list.pop()
  //this below line is affecting the result_list also,how to avoid this
  test_list[0][1]+=1

【问题讨论】:

    标签: python list


    【解决方案1】:

    现在是deepcopy 派上用场的时候了:

    from copy import deepcopy
    test_list=[[0,1],[2,3]]
    result_list=[]
    for i in range(3):
      result_list+=deepcopy(test_list)
      test_list.pop()
      test_list[0][1]+=1
    

    但正如@RafaelC 所说,它给出了错误:

    from copy import deepcopy
    test_list=[[0,1],[2,3]]
    result_list=[]
    for i in range(1):
      result_list+=deepcopy(test_list)
      test_list.pop()
      test_list[0][1]+=1
    

    @RafaelC 给出了另一个好主意:

    test_list=[[0,1],[2,3]]
    result_list=[]
    for i in range(1):
      result_list=(result_list + test_list ).copy()
      test_list.pop()
      test_list[0][1]+=1
    

    【讨论】:

      猜你喜欢
      • 2016-12-01
      • 2017-11-21
      • 2017-04-03
      • 1970-01-01
      • 2012-09-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-03
      相关资源
      最近更新 更多