python 中 set 集合支持的操作

集合是一個無序的不重複的可迭代對象,集合中的元素都是可哈希的(不可變的)

set([iterable]) 初始化一個集合

>>> set()
set()
>>> set([1,2,3,2,4])
{1, 2, 3, 4}

add(self, *args, **kwargs) 往集合裏添加元素

>>> a = {1,2,3}
>>> a.add(4)
>>> a
{1, 2, 3, 4}

clear 清除集合中的所有元素

>>> a = {1,2,3}
>>> a.clear()
>>> a
set()

copy() 對集合進行淺拷貝

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

difference(iterable) 獲取兩個集合的差異,返回一個新的集合

>>> a = {1,2,3}
>>> a.difference([1,2,5,6])
{3}

| 獲取兩個集合的並集,返回一個新的集合

>>> {1,2,3,4} | {1,2,5,6}
{1, 2, 3, 4, 5, 6}

& 獲取兩個集合的交集,返回一個新的集合

>>> {1,2,3,4} & {1,2,5,6}
{1, 2}

- 獲取兩個集合的差值,返回一個新的集合

>>> {1,2,3,4} - {1,2,5,6}
{3, 4}

^ 獲取兩個集合的對稱差集 (元素在倆集合中,但不會同時出現在二者中)

>>> a = {1,2,3}
>>> b = {3,5,6}
>>> a^b
{1, 2, 5, 6}

pop 隨機取出集合中的一個元素並返回這個元素

{1,2,5,6}.pop()

remove 移除集合中的指定元素,如果元素不存在拋出KeyError異常

>>> a = {1,2,3}
>>> a.remove(1)
>>> a
{2, 3}
>>> a.remove(5)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 5

difference_update(iterable) 移除集合中所有和可迭代對象重疊的元素

>>> a = {1,2,3}
>>> a.difference_update([1,3,5])
>>> a
{2}

discard() 移除集合中的一個元素,若這個元素不在集合中,沒事

>>> a = {1,2,3}
>>> a.discard(3)
>>> a
{1, 2}
>>> a.discard(6)
>>> a
{1, 2}

intersection(iterable) 返回集合和可迭代對象的交集

>>> a = {1,2,3}
>>> a.intersection([1,2,5,6])
{1, 2}

isdisjoint(iterable) 判斷集合和可迭代對象中是否有相同的元素

>>> a = {1,2,3}
>>> a.isdisjoint([1,2,5,6])
False
>>> a.isdisjoint([1,2])
False
>>> a.isdisjoint([5,6])
True

issubset(iterable) 判斷可迭代對象是否擁有集合中的全部元素

>>> a = {1,2,3}
>>> a.issubset({1})
False
>>> a.issubset({1,2,3,4})
True
>>> a.issubset([1,2,3,4])
True

issuperset(iterable) 判斷集合是否擁有可迭代對象中的全部元素

>>> a = {1,2,3}
>>> a.issuperset({1})
True
>>> a.issuperset({1,2,3,4})
False
>>> a.issuperset({0})
False

symmetric_difference(iterable) 返回可迭代對象和集合的對稱差集

>>> a = {1,2,3}
>>> a.symmetric_difference([1,2])
{3}
>>> a.symmetric_difference([1])
{2, 3}
>>> a.symmetric_difference([5])
{1, 2, 3, 5}

symmetric_difference_update (iterable) 更新集合,使集合中只保留可迭代對象和集合的對稱差集

>>> a = {1,2,3}
>>> a.symmetric_difference_update([1,3,5,6])
>>> a
{2, 5, 6}

union(iterable) 返回可迭代對象和集合的並集

>>> a = {1,2,3}
>>> a.union([1,2,5,6])
{1, 2, 3, 5, 6}

update(iterable) 將可迭代對象中集合中沒有的元素更新到集合中

>>> a = {1,2,3}
>>> a.update([1,2,5,6])
{1, 2, 3, 5, 6}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章