这两个都将给出一组:
shallow_copy_of_set = set(old_set)
要么:
shallow_copy_of_set = old_set.copy() #Which is more readable.
上述第一种方式没有给出一组集合的原因是它将设置正确的语法([old_set])。哪些不起作用,因为集合不能是其他集合中的元素,因为它们是不可变的,因为是可变的。但是,对于青蛙胶片来说,这不是真的。 frozenset(frozenset(frozenset([1,2,3])))== frozenset([1,2,3])。
因此,在Python(list,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是这些类型之一,那么
shallow_copy_of_x = type(x)(x) #Highly unreadable! But economical.
请注意,只有dict,set和frozenset具有内置的copy()方法。列表和字符串也可能是一个好主意,它具有一个copy()方法,以获得一致性和可读性。但是,至少在我正在测试的Python 2.7.3中,它们没有。