1. 程式人生 > 其它 >Python資料型別--集合簡介

Python資料型別--集合簡介

集合(set)是數學中的基本概念。它的嚴格定義非常抽象,我們可以簡單的認為集合是一個包含無序元素的容器,每一個元素都是不同的。集合之間可以有並、交等操作。Python內建了對集合型別的支援。

集合定義

Python中可以有兩種方法定義集合(set)物件:

  • 內建的Set()函式
  • 操作符{}

使用set()函式

set()函式需要一個可迭代型別(iterable)的引數,如列表、元組等。語法如下:

var_set = set(iterable)

例如:

>>> s1 = set(['a','b','c','d','e','a','b'])
>>> s1
{'b', 'c', 'd', 'a', 'e'}
>>> s2 = set((1,2,3,4,3,4))
>>> s2
{1, 2, 3, 4}

從上面的例子中可以發現集合的重要特點:

  • 集合不對元素進行排序
  • 集合會去掉重複的元素

集合去重的特點常被用來判別元素是否存在。

Python中字串也是可迭代型別,也可以作為set()函式的引數,生成字元集合。

>>> s3 = set('abcdefabc')
>>> s3
{'c', 'a', 'e', 'd', 'b', 'f'}

使用{}操作符

集合也可以使用{}操作符來定義,語法如下:

var_set = {item1, item2, ...}

例如:

>>> s4 = {'abc','foo','bar','def','abc','xyz','def'}
>>> s4
{'def', 'bar', 'abc', 'foo', 'xyz'}
>>> s5 = {1, 3, 4, 5, 6, 3, 6}
>>> s5
{1, 3, 4, 5, 6}

使用{}定義集合時,字串會作為一個獨立的元素放入集合,而使用set()函式時,字串作為一個可迭代型別會被遍歷後將字元放入集合。

定義空集合

對於表示式{},Python解釋為空的字典(dict),所以定義空的集合必須使用函式set()

>>> s6 = set()
>>> s6
set()
>>> s7 = {}
>>> s7
{}
>>> type(s7)
<class 'dict'>
>>> type(s6)
<class 'set'>
>>> s7.add('a')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'dict' object has no attribute 'add'
>>> s6.add('a')
>>> s6
{'a'}

使用集合

元素不可更改(immutable)

Python集合中的元素不需要具有相同或者同類的型別,可以包含不同型別的元素。

>>> s8 = {'a','b','c',1,2,3,4.5,('x','y','z')}
>>> s8
{1, 'c', 2, 3, 4.5, 'a', ('x', 'y', 'z'), 'b'}
>>>

Python集合型別是可修改型別(mutable),但是集合內的元素必須是不可修改型別(immutable)

>>> s8 = {'a','b','c',1,2,3,4.5,('x','y','z')}
>>> s8
{1, 'c', 2, 3, 4.5, 'a', ('x', 'y', 'z'), 'b'}
>>> s9 = {'a','b','c',['x','y','z']}
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'

由於元組型別(tuple)是不可修改型別,所以它可以出現在集合中,而列表(list)是可修改型別,所以不能出現在集合中。

操作集合元素

遍歷集合元素

使用for迴圈遍歷集合元素

>>> s = {'a','b','c','xyz',1,2,3}
>>> for x in s:
...     print(x)
...
1
c
2
3
a
xyz
b

元素歸屬判斷

使用in操作符判斷元素是否屬於集合

>>> s = set('ab')
>>> s
{'b', 'a'}
>>> 'a' in s
True
>>> 'x' in s
False

新增元素

使用集合add方法新增元素

>>> s = set('abc')
>>> s
{'b', 'c', 'a'}
>>> s.add('d')
>>> s.add('xyz')
>>> s
{'b', 'c', 'd', 'a', 'xyz'}
>>>

刪除元素

Python集合型別提供兩個方法刪除元素,分別是discardremove方法,兩者的唯一區別在於對不存在的元素的處理上:

  • 呼叫Discard刪除集合中不存在的元素,Discard不做任何處理
  • 呼叫Remove刪除集合中不存在的元素,Remove丟擲KeyError異常
>>> s = set('abcdefghijk')
>>> s
{'c', 'a', 'e', 'j', 'd', 'k', 'i', 'b', 'f', 'g', 'h'}
>>> s.discard('c')
>>> s
{'a', 'e', 'j', 'd', 'k', 'i', 'b', 'f', 'g', 'h'}
>>> s.remove('a')
>>> s
{'e', 'j', 'd', 'k', 'i', 'b', 'f', 'g', 'h'}
>>> s.discard('c')
>>> s
{'e', 'j', 'd', 'k', 'i', 'b', 'f', 'g', 'h'}
>>> s.remove('a')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'a'

Python集合還提供pop方法,pop隨機的刪除一個元素,並返回這個元素,如果是一個空集合,pop丟擲KeyError異常。

>>> s = set('ab')
>>> x = s.pop()
>>> x
'b'
>>> s
{'a'}
>>> y = s.pop()
>>> y
'a'
>>> s
set()
>>> z = s.pop()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'pop from an empty set'

Python還提供了clear方法,清空整個集合。

操作集合

Python提供了豐富的方法和函式操作集合物件

方法 使用 說明
len len(s) 返回集合s的元素個數
union s1.union(s2) 返回一個新的集合,它是集合s1與s2的並集
update s1.update(s2) 新增s2中所有元素到集合s1中
intersection s1.intersection(s2) 返回一個新的集合,它是集合s1與s2的交集
intersection_update s1.intersection_update(s2) 修改集合s1使它成為集合s1與s2的交集
difference s1.difference(s2) 返回一個新的集合,它包含所有在s1中但不在s2中的元素
difference_update s1.difference_update(s2) 從集合s1中刪除所有s2中的元素
symmetric_difference s1.symmetric_difference(s2) 返回一個新的集合,包含所有不同時在s1和s2中存在的元素
symmetric_difference_update s1.symmetric_difference_update(s2) 修改集合s1,使其等於s1.symmetric_difference(s2)
issubset s1.issubset(s2) 如果s1是s2的子集(相等也是子集),返回True
issuperset s1.issuperset(s2) 如果s2是s1的子集,返回True
isdisjoint s1.isdisjoint(s2) 如果s1和s2的交集為空,返回True

Python同時還為集合型別過載了操作符,使操作更加方便:

A | B <===> A.union(B)

A |= B <===> A.update(B)

A & B <===> A.intersection(B)

A &= B <===> A.intersection_update(B)

A - B <===> A.difference(B)

A -= B <===> A.difference_update(B)

A ^ B <===> A.symmetric_difference(B)

A ^= B <===> A.symmetric_difference_update(B)

A <= B <===> A.issubset(B)

A >= B <===> A.issuperset(B)

A < B <===> A <= B and A != B

A > B <===> A >= B and A != B

不可修改集合

Python同時也提供不可修改的集合型別(frozenset),除了不可修改外,它與集合型別(set)完全一樣,也就是說類似update這樣的方法,frozenset不能使用,但是類似union這樣的方法,它可以使用。

>>> fs = frozenset('abcdef')
>>> fs.add('x')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'frozenset' object has no attribute 'add'
>>> fs.update({'x','y'})
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'frozenset' object has no attribute 'update'
>>> fs.union({'x','y'})
frozenset({'c', 'd', 'a', 'y', 'b', 'f', 'e', 'x'})
>>> for x in fs:
...     print(x)
...
c
a
e
d
b
f
>>>

小結

Python內建set型別具有以下特點:

  • 集合元素是無序的
  • 集合元素都是不同的,不允許有相同元素出現在一個集合中
  • 集合物件本身是可修改的,但是集合元素是不可修改的

文章內容轉載至:http://www.coolbox.top/article/show?article_id=14


請相信自己

當我們迷茫,懶惰,退縮的時候 我們會格外的相信命運 相信一切都是命中註定

而當我們努力拼搏,積極向上時 我們會格外的相信自己

所以命運是什麼呢? 它是如果你習慣它 那它就會一直左右你

如果你想掙脫它 那它就成為你的阻礙 可如果你打破了它 那它就是你人生的墊腳石!


如果覺得這篇文章對你有小小的幫助的話,記得在右下角點個“推薦”哦,博主在此感謝!