如何在 Python 中克隆或复制集合?

2022-01-17 00:00:00 python clone set shallow-copy

问题描述

对于复制列表:shallow_copy_of_list = old_list[:].

对于复制字典:shallow_copy_of_dict = dict(old_dict).

但是对于 set,我担心类似的事情不会起作用,因为说 new_set = set(old_set) 会给出一个集合的集合?

But for a set, I was worried that a similar thing wouldn't work, because saying new_set = set(old_set) would give a set of a set?

但它确实有效.所以我在这里发布问题和答案以供参考.以防其他人有同样的困惑.

But it does work. So I'm posting the question and answer here for reference. In case anyone else has the same confusion.


解决方案

这两个都会给出一个集合的副本:

Both of these will give a duplicate of a set:

shallow_copy_of_set = set(old_set)

或者:

shallow_copy_of_set = old_set.copy() #Which is more readable.

上面的第一种方式没有给出一个集合的集合的原因是,正确的语法应该是set([old_set]).这是行不通的,因为 sets 不能是其他 sets 中的元素,因为它们是可变的,因此它们是不可散列的.但是,对于 frozenset 来说,情况并非如此,例如frozenset(frozenset(frozenset([1,2,3]))) == frozenset([1, 2, 3]).

The reason that the first way above doesn't give a set of a set, is that the proper syntax for that would be set([old_set]). Which wouldn't work, because sets can't be elements in other sets, because they are unhashable by virtue of being mutable. However, this isn't true for frozensets, so e.g. frozenset(frozenset(frozenset([1,2,3]))) == frozenset([1, 2, 3]).

因此,在 Python 中复制任何基本数据结构(列表、字典、集合、冻结集、字符串)实例的经验法则:

So a rule of thumb for replicating any of instance of the basic data structures in Python (lists, dict, set, frozenset, string):

a2 = list(a)      #a is a list
b2 = set(b)       #b is a set
c2 = dict(c)      #c is a dict
d2 = frozenset(d) #d is a frozenset
e2 = str(e)       #e is a string
#All of the above give a (shallow) copy.

所以,如果 x 是这两种类型中的任何一种,那么

So, if x is either of those types, then

shallow_copy_of_x = type(x)(x) #Highly unreadable! But economical.

请注意,只有 dictsetfrozenset 具有内置的 copy() 方法.为了统一和可读性,列表和字符串也有一个 copy() 方法可能是个好主意.但他们没有,至少在我正在测试的 Python 2.7.3 中.

Note that only dict, set and frozenset have the built-in copy() method. It would probably be a good idea that lists and strings had a copy() method too, for uniformity and readability. But they don't, at least in Python 2.7.3 which I'm testing with.

相关文章