Python set集合詳解

2021-09-26 02:29:39 字數 2499 閱讀 2071

python 中的集合,和數學中的集合概念一樣,用來儲存不重複的元素,即集合中的元素都是唯一的,互不相同。

從形式上看,和字典類似,python 集合會將所有元素放在一對大括號 {} 中,相鄰元素之間用「,」分隔,如下所示:

其中,elementn 表示集合中的元素,個數沒有限制。

從內容上看,同一集合中,只能儲存不可變的資料型別,包括整形、浮點型、字串、元組,無法儲存列表、字典、集合這些可變的資料型別,否則 python 直譯器會丟擲 typeerror 錯誤。比如說:

>>> }

traceback (most recent call last):

file "", line 1, in }

typeerror: unhashable type: 'dict'

>>>

traceback (most recent call last):

file "", line 1, in

typeerror: unhashable type: 'list'

>>> }

traceback (most recent call last):

file "", line 1, in }

typeerror: unhashable type: 'set'

並且需要注意的是,資料必須保證是唯一的,因為集合對於每種資料元素,只會保留乙份。例如:

>>> 

由於 python 中的 set 集合是無序的,所以每次輸出時元素的排序順序可能都不相同。

其實,python 中有兩種集合型別,一種是 set 型別的集合,另一種是 frozenset 型別的集合,它們唯一的區別是,set 型別集合可以做新增、刪除元素的操作,而 forzenset 型別集合不行。本節先介紹 set 型別集合,後續章節再介紹 forzenset 型別集合。

python 提供了 2 種建立 set 集合的方法,分別是使用 {} 建立和使用 set() 函式將列表、元組等型別資料轉換為集合。

1) 使用 {} 建立

在 python 中,建立 set 集合可以像列表、元素和字典一樣,直接將集合賦值給變數,從而實現建立集合的目的,其語法格式如下:

setname =
其中,setname 表示集合的名稱,起名時既要符合 python 命名規範,也要避免與 python 內建函式重名。

舉個例子:

a = 

print(a)

執行結果為:

2) set()函式建立集合

set() 函式為 python 的內建函式,其功能是將字串、列表、元組、range 物件等可迭代物件轉換成集合。該函式的語法格式如下:

setname = set(iteration)
其中,iteration 就表示字串、列表、元組、range 物件等資料。

例如:

set1 = set("c.biancheng.net")

set2 = set([1,2,3,4,5])

set3 = set((1,2,3,4,5))

print("set1:",set1)

print("set2:",set2)

print("set3:",set3)

執行結果為:

set1: 

set2:

set3:

注意,如果要建立空集合,只能使用 set() 函式實現。因為直接使用一對 {},python 直譯器會將其視為乙個空字典。

由於集合中的元素是無序的,因此無法向列表那樣使用下標訪問元素。python 中,訪問集合元素最常用的方法是使用迴圈結構,將集合中的資料逐一讀取出來。

例如:

a = 

for ele in a:

print(ele,end=' ')

執行結果為:

1 c (1, 2, 3)
和其他序列型別一樣,手動函式集合型別,也可以使用 del() 語句,例如:

a = 

print(a)

del(a)

print(a)

執行結果為:

traceback (most recent call last):

file "c:\users\mengma\desktop\1.py", line 4, in print(a)

nameerror: name 'a' is not defined

python set 集合最常用的操作是向集合中新增、刪除元素,以及集合之間做交集、並集、差集等運算。受到篇幅的限制,這些知識會放到下節進行詳細講解。

python set集合基礎

python set 基礎 集合 set 是乙個無序的不重複元素序列。可以使用大括號 或者 set 函式建立集合,注意 建立乙個空集合必須用 set 而不是 因為 是用來建立乙個空字典 a 1 2,3 4,1 print set a 結果 hello set hello.add b print he...

python set集合操作

set集合是乙個無序且不重複的集合。建立乙個set集合 name set sdd name 返回結果 add 功能 增加集合元素 name name.add d name 返回結果 name.add sd name 返回結果 clear 功能 清空集合元素 name name.clear name ...

PYTHON set 集合學習

建立乙個空的集合必須用set 因為 為dict。且set 只接受乙個引數 a type a dict a set type a set 集合中放的只能是數字 元組 字串,不能放字典,列表 set1 traceback most recent call last file line 1,in set1...