Python list.append 之后更改元素

标签 python python-3.x list

对于 args= ['', '0', 'P1', 'with', '10']students=[['1', '2', ' 3', 6]] 它打印:

[[['1', '2', '3', 6]]]
[[['10', '2', '3', 6]]]

预期输出是:

[[['1', '2', '3', 6]]]
[[['1', '2', '3', 6]]]

但它以某种方式改变了backup_list,有什么快速解决方案吗?

backup_list.append(students[:])
print(backup_list)
students[int(args[1])][0] = args[4]
print(backup_list)

最佳答案

[:] 进行浅拷贝。您需要一个深拷贝:

import copy

backup_list.append(copy.deepcopy(students))

完整程序:

import  copy

backup_list = []
args= ['', '0', 'P1', 'with', '10']
students=[['1', '2', '3', 6]]
backup_list.append(copy.deepcopy(students))
print(backup_list)
students[int(args[1])][0] = args[4]    
print(backup_list)

输出:

[[['1', '2', '3', 6]]]
[[['1', '2', '3', 6]]]

documentation解释浅复制和深复制之间的区别:

A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.

A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.

关于Python list.append 之后更改元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46988924/

相关文章:

python - 如何在正则表达式模式中查找正则表达式模式

python - 如何在 Python 中的执行之间保留数据

python - Ubuntu 正在扼杀我的计算

python-3.x - 编写删除重复元素的程序时列表索引超出范围

python - 我怎样才能使列表理解具有 "or?"

Python:在两个 python 安装之间共享 python 站点包库

django - 如何迁移django中的特定表

python - 无法在鼠标悬停时更改 tkinter Canvas 背景颜色?

python - 连接并扁平化两个嵌套的 python 列表

python:按索引将列表拆分为n个子列表