python可变集合和不可变集合_不可变集合frozenset

* 作者:煮酒品茶 tea

* 博客:http://www.zwhset.com http://cwtea.blog.51cto.com

* 目前在京峰教育担任python讲师

# 0、不可变集合frozenset

> frozenset是不可变的集合, 简单说就是不能修改的set集合, 它和set集合类似,区别在于一个可变, 另一个不可变,其它的功能一样。 很像list和tuple的区别

# 1、函数原型

~~~

frozenset() -> empty frozenset object # 创建空的 frozense集合

frozenset(iterable) -> frozenset object # 从一个iterable转换成frozense集合

difference(...)

Return the difference of two or more sets as a new set.

(i.e. all elements that are in this set but not the others.)

intersection(...)

Return the intersection of two or more sets as a new set.

(i.e. elements that are common to all of the sets.)

isdisjoint(...)

Return True if two sets have a null intersection.

issubset(...) # 子集判断

Report whether another set contains this set.

issuperset(...) # 父集判断

Report whether this set contains another set.

symmetric_difference(...)

Return the symmetric difference of two sets as a new set.

(i.e. all elements that are in exactly one of the sets.)

union(...) # 并集

Return the union of sets as a new set.

~~~

# 2、样例

~~~

>>> frozen_set = frozenset() # 创建一个空的frozenset集合

>>> frozen_set

frozenset([])

>>>

>>> frozen_set2 = frozenset('abcdefghigkomnopqrszuvwxyz') # 从一个str创建一个frozenset集合

>>> frozen_set2

frozenset(['a', 'c', 'b', 'e', 'd', 'g', 'f', 'i', 'h', 'k', 'm', 'o', 'n', 'q', 'p', 's', 'r', 'u', 'w', 'v', 'y', 'x', 'z'])

>>>

>>> frozen_set2 = frozenset(['a','b','c','d','e']) # 从一个list创建一个frozenset集合

>>> frozen_set2

frozenset(['a', 'c', 'b', 'e', 'd'])

~~~

# 3、应用场景:

如果要创建和使用一个不会修改的集合可以用frozenset, 能用不可变的对就用不可变的对象

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值