如何在python中正确复制列表 [英] How to properly copy a list in python

查看:62
本文介绍了如何在python中正确复制列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like to keep track of bubble sorting algorithm's intermediate states at each iteration. I've tried to cache them in dictionary while loop is running, but i keep getting the same state all the time

这是我的代码:

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

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

As you can see, it outputs sorted list each time. What am I missing here?

推荐答案

问题是,该行 cache [f'iter {iter}'] = new_lst 高速缓存字典中的对象以及new_list变量都指向同一对象.在下一次互动中 new_lst = lst 用新对象覆盖它,现在缓存lst和new_list指向同一个对象.您需要做的是创建对象的真实"副本.为此,您可以使用 copy 包.您还应该阅读浅复制和深复制之间的区别,因为它们是非常基础的,并且如果不正确理解,还会带来许多问题.

The problem is, that with the line cache[f'iter{iter}'] = new_lst both the object in the cache dictionary as well as the new_list variable point to the same object. In the next interation then new_lst = lst overwrites it with a new object and now the cache, lst and new_list point to the same object. What you need to do, is to create a 'real' copy of the object. For that you can use the copy package. You should also read about the difference between shallow and deep copy as they are very fundamental and the source of a multitude of problems if not understood correctly.

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

这篇关于如何在python中正确复制列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆