gpt4 book ai didi

python-3.x - python : How to copy a list of a dictionaries

转载 作者:行者123 更新时间:2023-12-05 08:30:58 24 4
gpt4 key购买 nike

Python 3。我试图在不改变原始列表的情况下复制字典列表。这似乎与复制列表的工作方式不同:

词典列表

list_of_dict = [{"A":"a", "B": "b"}]    
table_copy = list(list_of_dict)
for x in table_copy:
x['B'] = 1

print(list_of_dict)
print(table_copy)

产量

[{'A': 'a', 'B': 1}]
[{'A': 'a', 'B': 1}]

作为引用,这是复制列表的样子:

orig_list = [1,2,3]
copy_list = list(orig_list)
copy_list[1] = "a"
print(orig_list)
print(copy_list)

产生我们期望的结果

[1, 2, 3]
[1, 'a', 3]

您如何实际复制字典列表?

最佳答案

通过这行代码,table_copy = list(list_of_dict) 您正在创建一个新的指针(变量) 但底层元素未被复制(这是浅拷贝)

list_of_dict = [{"A":"a", "B": "b"}]    
table_copy = list(list_of_dict)

id(list_of_dict)
Out[8]: 2208287332232

id(table_copy)
Out[9]: 2208275740680

id(list_of_dict[0])
Out[10]: 2208275651624

id(table_copy[0])
Out[11]: 2208275651624 <== equal to id(list_of_dict[0])

你应该使用 copy来自标准库的模块,带有两个有用的函数

copy(x):

Return a shallow copy of x.

deepcopy(x):

Return a deep copy of x.

针对您的问题,

from copy import deepcopy

list_of_dict = [{"A":"a", "B": "b"}]
table_copy = deepcopy(list_of_dict)

当你有一个复杂的对象,即包含其他对象的对象时,经验法则是使用deepcopy

来自文档

The difference between shallow and deep copying is only relevant for compound objects (objects that contain other objects, like lists or class instances):

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-3.x - python : How to copy a list of a dictionaries,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60815400/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com