1. 程式人生 > >Python 中的集合 --set

Python 中的集合 --set

前言

在Python中,我們用[]來表示列表list,用()來表示元組tuple,那{}呢?{}不光可用來定義字典dict,還可以用來表示集合set

 

集合 set

 

集合(set)是一個無序的不重複元素序列,集合中的元素不能重複且沒有順序,所以不能通過索引和分片進行操作。

 

如何建立set

 

•set() 建立一個集合,需要提供一個序列(可迭代的物件)作為輸入引數:

#字串
>>> set('abc')
{'a', 'b', 'c'}
#列表
>>> set(['a','b','c'])
{'a', 'b', 'c'}
#元組
>>> set(('a','b','c'))
{'a', 'b', 'c'}

# 集合中的元素不重複
>>> set('aabc')
{'a', 'b', 'c'}

#整數
>>> set(123)

Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    set(123)
TypeError: 'int' object is not iterable

•{}

>>> {1,2,3}
{1, 2, 3}
>>> a = {1,2,3}
>>> type(a)
<class 'set'>

但注意 利用 {} 來建立集合不能建立空集合,因為 {} 是用來創造一個空的字典

 

set的常用方法

 

•set`的新增和刪除,更新

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

#新增元素
>>> a.add('d')
>>> a
{'a', 'b', 'd', 'c'}

#重複新增無效果
>>> a.add('d')
>>> a
{'a', 'b', 'd', 'c'}

#刪除元素
>>> a.remove('c')
>>> a
{'a', 'b', 'd'}

#update 把要傳入的元素拆分,作為個體傳入到集合中
>>> a.update('abdon')
>>> a
{a', 'b', 'd', 'o', 'n' }

set的集合操作符

 

 

 

 

>>> a = set('abc')
>>> b = set('cdef')
>>> a&b
{'c'}
>>> a | b  
{'a', 'b', 'f', 'c', 'd', 'e'}
>>> a -b
{'a', 'b'}
>>> 'a' in a
True
>>> 'e' in a
False
>>> a != b
True
>>> a == b
False

集合還有不可變集合frozenset,用的不多,有興趣的同學可以自行學習下!

 更多交流公眾號:猿