本文介绍了如何在Python中克隆或复制集合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

用于复制列表: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]).这是行不通的,因为set不能是其他set中的元素,因为它们由于可变而无法散列.但是,对于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中复制基本数据结构的任何实例(列表,字典,集合,frozenset,字符串)的经验法则:

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.

这篇关于如何在Python中克隆或复制集合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-17 07:12