­

python之集合(set)學習

  • 2020 年 1 月 17 日
  • 筆記

集合(set)

集合是一個無序的不重複元素序列,使用大括號({})、set()函數創建集合。

注意:創建一個空集合必須用set()而不是{},因為{}是用來創建一個空字典。

集合是無序的、不重複的、沒有索引的

1 a = {'hello','ni','hao','hi','ni','hao'}  2  3 print(a)     # 輸出結果沒有重複項,且無序  4 # print(a[1])   # TypeError: 'set' object does not support indexing

輸出結果:

{'ni', 'hao', 'hello', 'hi'}

添加集合元素

添加單個元素:

1 a = {'hello','ni','hao','hi','ni','hao'}  2 print(a)  3  4 a.add('wo')  5 print(a)  6  7 a.add('hi')     # 如果元素已存在,則不進行任何操作。  8 print(a)     

輸出結果:

{'hi', 'ni', 'hao', 'hello'}  {'hello', 'hi', 'wo', 'ni', 'hao'}  {'hello', 'hi', 'wo', 'ni', 'hao'}

添加多個元素、列表元素、字典元素

 1 a = {'hello','ni','hao','hi','ni','hao'}   2 print(a)   3   4 a.update("me", 'da')   5 print(a)   6   7 a.update({'user': 'name', 'pwd': 'mima'})   8 print(a)   9  10 print(len(a))  11 a.update([1, 2, 3, 4])  12 print(a)  13  14 a.update(['abc', 'word', 'x'])  15 print(a)

輸出結果:

{'hi', 'hao', 'hello', 'ni'}  {'hello', 'hao', 'e', 'ni', 'hi', 'd', 'a', 'm'}  {'hello', 'hao', 'e', 'ni', 'hi', 'user', 'pwd', 'd', 'a', 'm'}  {1, 2, 3, 4, 'hello', 'hao', 'e', 'ni', 'hi', 'user', 'pwd', 'd', 'a', 'm'}  {1, 2, 3, 4, 'hello', 'abc', 'hao', 'e', 'ni', 'hi', 'user', 'pwd', 'd', 'word', 'a', 'm', 'x'}

輸出結果有些出人意料,使用add添加單個元素時,不管該元素時單個字符還是字符串,都作為一個元素添加,而使用update則將字符串元素拆開為單個字符添加。

而且添加的元素為字典時,可以發現,key值是按照字符串添加的,而value值也是拆開為單個字符添加。

添加的元素為列表時,是將列表元素拆開,作為一個個單獨的元素添加進集合,即使列表元素中有字符串,但是不在拆分該字符串。

刪除集合元素

刪除集合元素有三種方法:set.remove()、set.discard()、set.pop()

 1 a = {'hello','ni','hao','hi','ni','hao'}   2   3 a.remove('hao')   4 print(a)   5   6 # a.remove('nihao')   # 如果元素不存在,會發生錯誤   7 # print(a)   8 a.discard('nihao')  # 如果元素不存在,不會發生錯誤   9 print(a)  10  11 a.pop()     # 隨機刪除集合中的一個元素,在交互模式中,刪除集合中的第一個元素(排序後的第一個元素)  12 print(a)

輸出結果:

{'ni', 'hi', 'hello'}  {'ni', 'hi', 'hello'}  {'hi', 'hello'}

清空集合元素:

1 a = {'hello','ni','hao','hi','ni','hao'}  2  3 a.clear()  4 print(a)

輸出結果:

set()

遍歷集合

因為集合是無序的,所以不能使用索引,那麼只能使用for循環來遍歷。

1 a = {'hello','ni','hao','hi','ni','hao'}  2  3 for x in a:  4     print(x)

輸出結果:

hao  ni  hi  hello

學到這裡,Python的基本數據類型已經簡單的介紹完了,但是肯定不是這麼點,還有更深更細節的知識就不是現階段應該學的,那需要以後慢慢積累,多加練習才能掌握的。