本文介绍了如何在 Python 中复制像元组这样的不可变对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

copy.copy()copy.deepcopy() 只是复制像元组这样的不可变对象的引用.如何在不同的内存位置创建第一个不可变对象的副本?

copy.copy() and copy.deepcopy() just copy the reference for an immutable object like a tuple.How can I create a duplicate copy of the first immutable object at a different memory location?

推荐答案

您正在寻找 deepcopy.

from copy import deepcopy

tup = (1, 2, 3, 4, 5)
put = deepcopy(tup)

诚然,这两个元组的 ID 会指向同一个地址.因为元组是不可变的,所以真的没有理由创建另一个完全相同的副本.但是,请注意元组可以包含可变元素,并且 deepcopy/id 的行为与您预期的一样:

Admittedly, the ID of these two tuples will point to the same address. Because a tuple is immutable, there's really no rationale to create another copy of it that's the exact same. However, note that tuples can contain mutable elements to them, and deepcopy/id behaves as you anticipate it would:

from copy import deepcopy
tup = (1, 2, [])
put = deepcopy(tup)
tup[2].append('hello')
print tup # (1, 2, ['hello'])
print put # (1, 2, [])

这篇关于如何在 Python 中复制像元组这样的不可变对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-21 12:16