python怎么复制,如何在Python中克隆或复制集合?

本文探讨了如何在Python中复制集合,包括列表、字典和集合。通过示例展示了set(old_set)和old_set.copy()两种创建集合副本的方法,并解释了为何不会产生集合内的集合。同时,提到了frozenset的特性以及复制基本数据结构的一般规则。
摘要由CSDN通过智能技术生成

For copying a list: shallow_copy_of_list = old_list[:].

For copying a dict: shallow_copy_of_dict = dict(old_dict).

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)

Or:

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

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]).

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.

So, if x is either of those types, then

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

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值