Python: Set Types

set v.s. frozenset

A set object is an unordered collection of distinct hashable objects.

  • The set type is mutable — the contents can be changed using methods like add() and remove(). Since it is mutable, it has no hash value and cannot be used as either a dictionary key or as an element of another set.
  • The frozenset type is immutable and hashable — its contents cannot be altered after it is created; it can therefore be used as a dictionary key or as an element of another set.

Class

class set([iterable])
class frozenset([iterable])
Return a new set or frozenset object whose elements are taken from iterable. The elements of a set must be hashable. To represent sets of sets, the inner sets must be frozenset objects. If iterable is not specified, a new empty set is returned.

Non-empty sets (not frozensets) can be created by placing a comma-separated list of elements within braces, for example: {'jack', 'sjoerd'}, in addition to the set constructor.

Note: to create an empty set you have to use set(), not{}; the latter creates an empty dictionary.

>>> a = {}
>>> type(a)
<class 'dict'>
>>> 
>>> a = set()
>>> type(a)
<class 'set'>

set and frozenset 's Methods

Membership

  • In a mathematics

    • If B is a set and x is one of the objects of B, this is denoted x ∈ B, and is read as "x belongs to B", or "x is an element of B".
    • If y is not a member of B then this is written as y ∉ B, and is read as "y does not belong to B".
  • In Python

    • x in s
      Test x for membership in s.

    • x not in s
      Test x for non-membership in s.

>>> a = {1, 2, 3}
>>> 1 in a
True
>>> 4 in a
False
>>> 4 not in a
True

Subsets

  • In mathematics

    • If every member of set A is also a member of set B, then A is said to be a subset of B, written A ⊆ B (also pronounced A is contained in B). Equivalently, we can write B ⊇ A, read as B is a superset of A, B includes A, or B contains A.

    • If A is a subset of, but not equal to, B, then A is called a proper subset of B, written A ⊊ B (A is a proper subset of B) or B ⊋ A (B is a proper superset of A).

  • In Python

    • issubset(other)

      • set <= other
        Test whether every element in the set is in other.
      • set < other
        Test whether the set is a proper subset of other, that is, set <= other and set != other
        .
    • issuperset(other)

      • set >= other
        Test whether every element in other is in the set.

      • set > other
        Test whether the set is a proper superset of other, that is, set >= other and set != other
        .

>>> a = {1, 2, 3}
>>> b = {1, 2}
>>> c = {3, 4}
>>> d = {1, 2, 3}
>>> 
>>> b.issubset(a)
True
>>> c.issubset(a)
False
>>> a.issuperset(b)
True
>>> a.issubset(d)
True
>>> d.issubset(a)
True

Cardinality

  • In mathematics

    • The cardinality | S | of a set S is "the number of members of S."
  • In Python

    • len(s)
      Return the number of elements in set s (cardinality of s).
>>> a = {1, 2, 3}
>>> len(a)
3

Union

  • In mathematics

    • Two sets can be "added" together. The union of A and B, denoted by A ∪ B, is the set of all things that are members of either A or B.
  • In Python

    • union(*others)
      set | other | ...
      Return a new set with elements from the set and all others.
>>> a = {1, 2, 3}
>>> b = {3, 4}
>>> 
>>> a.union(b)
{1, 2, 3, 4}
>>> a | b
{1, 2, 3, 4}

Intersections and Disjoint

  • In mathematics

    • A new set can also be constructed by determining which members two sets have "in common". The intersection of A and B, denoted by A ∩ B, is the set of all things that are members of both A and B.
    • If A ∩ B = ∅, then A and B are said to be disjoint.
  • In Python

    • intersection(*others)
      set & other & ...
      Return a new set with elements common to the set and all others.
    • isdisjoint(other)
      Return True if the set has no elements in common with other. Sets are disjoint if and only if their intersection is the empty set.
>>> a = {1, 2, 3}
>>> b = {3, 4}
>>> 
>>> a.intersection(b)
{3}
>>> a & b
{3}
>>> a.isdisjoint(b)
False

Difference

  • In mathematics

    • If A and B are sets, then the relative complement of A in B, also termed the set-theoretic difference of B and A, is the set of elements in B but not in A.denoted by B \ A (or B − A). Note that it is valid to "subtract" members of a set that are not in the set.
  • In Python

    • difference(*others)
      set - other - ...
      Return a new set with elements in the set that are not in the others.
>>> a = {1, 2, 3}
>>> b = {3, 4}
>>> 
>>> a - b
{1, 2}
>>> a.difference(b)
{1, 2}

Symmetric difference

  • In mathematics
    • The symmetric difference, also known as the disjunctive union, of two sets is the set of elements which are in either of the sets and not in their intersection.
  • In Python
    • symmetric_difference(*other)
      set ^ other
      Return a new set with elements in either the set or other but not both.
>>> a = {1, 2, 3}
>>> b = {3, 4}
>>> 
>>> a.symmetric_difference(b)
{1, 2, 4}
>>> a ^ b
{1, 2, 4}

copy

Return a new set with a shallow copy of s.

>>> a
{1, 2, 3}
>>> b = a.copy
>>> id(a) == id(b)
False

some other methods(only for set)

The following table lists operations available for set that do not apply to immutable instances of frozenset:

  • update(*others)
    set |= other | ...
    Update the set, adding elements from all others.
>>> a
{1, 2, 3}
>>> b
{3, 4}
>>> id_before = id(a)
>>> a |= b
>>> a
{1, 2, 3, 4}
>>> id_before == id(a)
True
  • intersection_update(*others)
    set &= other & ...
    Update the set, keeping only elements found in it and all others.
>>> a
{1, 2, 3}
>>> b
{3, 4}
>>> a = {1, 2, 3}
>>> a &= b
>>> a
{3}
  • difference_update(*others)
    set -= other | ...
    Update the set, removing elements found in others.
>>> a = {1, 2, 3}
>>> b
{3, 4}
>>> a -= b
>>> a
{1, 2}
  • symmetric_difference_update(other)
    set ^= other
    Update the set, keeping only elements found in either set, but not in both.
>>> a = {1, 2, 3}
>>> b
{3, 4}
>>> a ^= b
>>> a
{1, 2, 4}
  • add(elem)
    Add element elem to the set.
>>> a = {1, 2, 3}
>>> 
>>> a.add(4)
>>> a
{1, 2, 3, 4}
  • remove(elem)
    Remove element elem from the set. Raises KeyError if elem is not contained in the set.
>>> a
{1, 2, 3, 4}
>>> a.remove(4)
>>> a
{1, 2, 3}
>>> a.remove(4)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 4
  • discard(elem)
    Remove element elem from the set if it is present.
>>> a
{1, 2, 3}
>>> a.discard(4)
>>> a.discard(2)
>>> a
{1, 3}
  • pop()
    Remove and return an arbitrary element from the set. Raises KeyError if the set is empty.
>>> a = {1}
>>> a.pop()
1
>>> a.pop()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'pop from an empty set'
  • clear()
    Remove all elements from the set.
>>> a = {1, 2}
>>> 
>>> a.clear()
>>> a
set()

Note

  • non-operator v.s. operator

the non-operator versions of union(), intersection(), difference(), and symmetric_difference(), issubset(), and issuperset() methods will accept any iterable as an argument. In contrast, their operator based counterparts require their arguments to be sets.

>>> a = {1, 2, 3}
>>> c = [2, 4]
>>> 
>>> a.union(c)
{1, 2, 3, 4}
>>> a | c
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for |: 'set' and 'list'
  • comparions
    Both set and frozenset support set to set comparisons.
    • Two sets are equal if and only if every element of each set is contained in the other (each is a subset of the other).
    • A set is less than another set if and only if the first set is a proper subset of the second set (is a subset, but is not equal).
    • A set is greater than another set if and only if the first set is a proper superset of the second set (is a superset, but is not equal).
>>> a = {1, 2, 3}
>>> b = {1, 2}
>>> c = {3, 4}
>>> a > b
True
>>> a > c
False
>>> d = {1, 2, 3}
>>> a == d
True
  • {} v.s. set()

Why is that? Haaaa...O!

>>> a = {'abc'}
>>> a
{'abc'}
>>> b = set('abc')
>>> b
{'c', 'a', 'b'}
>>> c = set(['abc'])
>>> c
{'abc'}
>>> d = set(('abc'))
>>> d
{'c', 'a', 'b'}

>>> ('abc')
'abc'
>>> ('abc',)
('abc',)
>>> e = set(('abc',))
>>> e
{'abc'}

read more

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 195,980评论 5 462
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 82,422评论 2 373
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 143,130评论 0 325
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,553评论 1 267
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,408评论 5 358
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,326评论 1 273
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,720评论 3 386
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,373评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,678评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,722评论 2 312
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,486评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,335评论 3 313
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,738评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,009评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,283评论 1 251
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,692评论 2 342
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,893评论 2 335

推荐阅读更多精彩内容