如何在 Python 中复制像元组这样的不可变对象?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15214404/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I copy an immutable object like tuple in Python?
提问by
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?
copy.copy()和copy.deepcopy()刚才复制的参考像一个元组不可变对象。如何在不同的内存位置创建第一个不可变对象的副本?
回答by lvc
Add the empty tuple to it:
向其中添加空元组:
>>> a = (1, 2, 3)
>>> a is a+tuple()
False
Concatenating tuples always returns a new distinct tuple, even when the result turns out to be equal.
连接元组总是返回一个新的不同元组,即使结果是相等的。
回答by Makoto
You're looking for deepcopy.
您正在寻找deepcopy.
from copy import deepcopy
tup = (1, 2, 3, 4, 5)
put = deepcopy(tup)
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:
诚然,这两个元组的 ID 将指向同一个地址。因为元组是不可变的,所以真的没有理由创建另一个完全相同的副本。但是,请注意元组可以包含可变元素,并且 deepcopy/id 的行为与您预期的一样:
from copy import deepcopy
tup = (1, 2, [])
put = deepcopy(tup)
tup[2].append('hello')
print tup # (1, 2, ['hello'])
print put # (1, 2, [])
回答by Wiki Zhao
try this:
尝试这个:
tup = (1,2,3)
nt = tuple(list(tup))
And I think adding an empty tuple is much better.
而且我认为添加一个空元组要好得多。

