0
点赞
收藏
分享

微信扫一扫

#yyds干货盘点#python内置函数之集合类型 --- set, frozenset

set 对象是由具有唯一性的 hashable 对象所组成的无序多项集。 常见的用途包括成员检测、从序列中去除重复项以及数学中的集合类计算,例如交集、并集、差集与对称差集等等。 

与其他多项集一样,集合也支持 x in set​, len(set) 和 for x in set。 作为一种无序的多项集,集合并不记录元素位置或插入顺序。 相应地,集合不支持索引、切片或其他序列类的操作。

class set([iterable])

class frozenset([iterable])

返回一个新的 set 或 frozenset 对象,其元素来自于 iterable。 集合的元素必须为 hashable。 要表示由集合对象构成的集合,所有的内层集合必须为 ​frozenset​ 对象。 如果未指定 iterable,则将返回一个新的空集合。

集合可用多种方式来创建:

  • 使用花括号内以逗号分隔元素的方式: {'jack', 'sjoerd'}
  • 使用集合推导式: {c for c in 'abracadabra' if c not in 'abc'}
  • 使用类型构造器: ​​set()​​, ​​set('foobar')​​, ​​​set(['a', 'b', 'foo'])​


len(s)

返回集合 s 中的元素数量(即 s 的基数)。

x in s

检测 x 是否为 s 中的成员。

x not in s

检测 x 是否非 s 中的成员。

​isdisjoint​​(other)

如果集合中没有与 other 共有的元素则返回 ​​True​​。 当且仅当两个集合的交集为空集合时,两者为不相交集合。

​issubset​​(other)

​set <= other​

检测是否集合中的每个元素都在 other 之中。

​set < other​

检测集合是否为 other 的真子集,即 ​​set <= other and set != other​​。

​issuperset​​(other)

​set >= other​

检测是否 other 中的每个元素都在集合之中。

​set > other​

检测集合是否为 other 的真超集,即 ​​set >= other and set != other​​。

​union​​(*others)

​set | other | ...​

返回一个新集合,其中包含来自原集合以及 others 指定的所有集合中的元素。

​intersection​​(*others)

​set & other & ...​

返回一个新集合,其中包含原集合以及 others 指定的所有集合中共有的元素。

​difference​​(*others)

​set - other - ...​

返回一个新集合,其中包含原集合中在 others 指定的其他集合中不存在的元素。

​symmetric_difference​​(other)

​set ^ other​

返回一个新集合,其中的元素或属于原集合或属于 other 指定的其他集合,但不能同时属于两者。

​copy​​()

返回原集合的浅拷贝。

举报

相关推荐

0 条评论