Python集合set的用法

2021-08-29 01:19:32 字數 1157 閱讀 6042

建立集合(括號中只能有乙個引數):

>>> s = set('set')

>>> s

>>> s = set(['set'])

>>> s

增加乙個元素:

>>> s

>>> s.add('python')

>>> s

增加多個元素(求並集):

>>> s

>>> s.update('py')

>>> s

>>> s.update(['py','st'])

>>> s

刪除乙個元素:

>>> s

>>> s.remove('st')

>>> s

求交集:

>>> a = set([1,2,3])

>>> b = set([2,3,4])

>>> a & b

求並集:

>>> a | b

求差集:

>>> a - b

>>> b - a

集合是無序的,也不能對其進行索引或切片:

>>> a[0]

traceback (most recent call last):

file "", line 1, in a[0]

typeerror: 'set' object does not support indexing

>>> a[:]

traceback (most recent call last):

file "", line 1, in a[:]

typeerror: 'set' object is not subscriptable

判斷乙個集合是否是另乙個子集:

>>> a

>>> b

>>> b.issubset(a)

true

或》 b <= a

true

python 集合概念set用法

python中set的用法 python 的集合型別和 其他語言類似,是乙個無序不重複元素集,我在之前學過的其他的語言好像沒有見過這個型別,基本功能包括關係測試和消除重複元素.集合物件還支援union 聯合 intersection 交 difference 差 和sysmmetricdiffere...

python中set集合的用法

python的set和其他語言類似,是乙個無序不重複元素集,基本功能包括關係測試和消除重複元素.集合物件還支援union 聯合 intersection 交 difference 差 和sysmmetric difference 對稱差集 等數 算.sets 支援 x in set,len set ...

Python的set 集合 型別常見用法

記錄下,方便自己查閱,持續更正補充。集合 set 是乙個無序的無重複元素序列。可以使用大括號 或者 set 函式建立集合,注意 建立乙個空集合必須用 set 而不是 因為 是用來建立乙個空字典。1.檢查列表哪些元素重複了 eg a a b s set x for x in eg if eg.coun...