【问题标题】:How to properly copy a list in python如何在python中正确复制列表
【发布时间】:2020-11-10 14:54:49
【问题描述】:

我想在每次迭代时跟踪冒泡排序算法的中间状态。我试图在循环运行时将它们缓存在字典中,但我一直保持相同的状态

这是我的代码:

def bubblesort(lst):
    cache = {}
    # Swap the elements to arrange in order
    iter = 0
    for iter_num in range(len(lst)-1,0,-1):
        new_lst = lst
        for idx in range(iter_num):
            iter += 1
            if new_lst[idx]>new_lst[idx+1]:
                new_lst[idx], new_lst[idx+1] = new_lst[idx+1], new_lst[idx]
            cache[f'iter{iter}'] = new_lst
    return cache

这是输出:

{'iter1': [50, 119, 194, 365, 608, 788, 851, 879, 960],
 'iter2': [50, 119, 194, 365, 608, 788, 851, 879, 960],
 'iter3': [50, 119, 194, 365, 608, 788, 851, 879, 960],
 'iter4': [50, 119, 194, 365, 608, 788, 851, 879, 960],
 'iter5': [50, 119, 194, 365, 608, 788, 851, 879, 960],
 'iter6': [50, 119, 194, 365, 608, 788, 851, 879, 960],
 'iter7': [50, 119, 194, 365, 608, 788, 851, 879, 960],
 'iter8': [50, 119, 194, 365, 608, 788, 851, 879, 960],
 'iter9': [50, 119, 194, 365, 608, 788, 851, 879, 960],
 'iter10': [50, 119, 194, 365, 608, 788, 851, 879, 960],
...}

如您所见,它每次都会输出排序列表。我在这里错过了什么?

【问题讨论】:

标签: python deep-copy shallow-copy


【解决方案1】:

问题是,那行 cache[f'iter{iter}'] = new_lst 缓存字典中的对象和 new_list 变量都指向同一个对象。 然后在下一个交互中 new_lst = lst 用新对象覆盖它,现在缓存、lst 和 new_list 指向同一个对象。 您需要做的是创建对象的“真实”副本。为此,您可以使用 copy 包。 您还应该了解shallow and deep copy 之间的区别,因为它们非常基础,如果理解不正确,则会导致大量问题。

from copy import copy
[...]
cache[f'iter{iter}'] = copy(new_lst)

【讨论】:

  • 是的!谢谢你,我没有看到的愚蠢错误:)
猜你喜欢
  • 2020-06-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-11
  • 2021-10-09
  • 2023-01-08
  • 2016-02-05
  • 2021-07-04
相关资源
最近更新 更多