python - 如何在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],
...}
如您所见,它每次都输出排序列表。我在这里想念什么?
解决方案
问题是,
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)
推荐阅读
- hibernate - Override hibernate 物理命名策略 | @Column 不工作
- python-3.x - Flask 应用程序中的 FloatField 条目出现问题
- javascript - 按钮单击上的 javascript 功能有时有效
- c++ - 如何修复超过 1 分钟规则的 Collatz 序列码?
- reactjs - 反应选择没有选择选项
- python - 熊猫:选择最后“N”列
- react-native - 无法解析模块`@expo/vector-icons/FontAwesome`
- python - Python Argparse:可选参数中的参数
- flutter - Flutter 的 PopupMenuButton 中未显示图标
- javascript - 在 HTML 上显示多个 JSON 响应作为单个值