首页 > 解决方案 > 如何在python中正确复制列表

问题描述

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

这是我的代码:

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],
...}

如您所见,它每次都输出排序列表。我在这里想念什么?

标签: pythondeep-copyshallow-copy

解决方案


问题是, 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)

推荐阅读