自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

詳解Python集合Set,建議珍藏??!

開(kāi)發(fā) 后端
在前面的幾篇Python的文章中,我們介紹了Python的多種不同類(lèi)型的對(duì)象:字符串、列表、元組、字典。

[[422165]]

本文轉(zhuǎn)載自微信公眾號(hào)「尤而小屋」,作者尤而小屋。轉(zhuǎn)載本文請(qǐng)聯(lián)系尤而小屋公眾號(hào)。

大家好,我是Peter~

在前面的幾篇Python的文章中,我們介紹了Python的多種不同類(lèi)型的對(duì)象:字符串、列表、元組、字典。它們有各自的特點(diǎn):

  • 字符串str:存在索引,字符串中的元素是可以重復(fù)的,元素是不可變,不能修改的
  • 列表list:也能夠進(jìn)行索引和切片操作,元素可以修改,是可變的
  • 元組tuple:可以看成是不能進(jìn)行修改的“列表”;元素不能直接修改,也可以進(jìn)行索引和切片操作,類(lèi)似列表
  • 字典:Python中十分常用,鍵值對(duì)組成,鍵必須是比可變的數(shù)據(jù)類(lèi)型(比如元組),值可以是任意數(shù)據(jù);字典是無(wú)序的

如果說(shuō)元組是列表和字符串的雜合體,那么集合可以看做是列表和字典的雜合體

Python連載文章

本文的整體目錄結(jié)構(gòu):

集合創(chuàng)建

集合set的創(chuàng)建有兩種方法:

通過(guò)set函數(shù)創(chuàng)建,空集合只能用這種方式

通過(guò){}來(lái)創(chuàng)建

空集合

  1. s1 = set()  # 空集合 
  2. s1 

set()

  1. type(s1) 

set

注意:空集合必須使用set函數(shù)來(lái)創(chuàng)建,因?yàn)閧}是用來(lái)創(chuàng)建空字典的

非空集合

使用花括號(hào)創(chuàng)建

  1. s2 = {1,2,3,4}   
  2. s2 

{1, 2, 3, 4}

  1. type(s2) 

set

使用set函數(shù)創(chuàng)建

  1. s3 = set([9,8,7,6])  # 將元素用列表裝起來(lái),set只能有一個(gè)參數(shù) 
  2. s3 

{6, 7, 8, 9}

  1. type(s3) 

set

  1. s4 = set((11,22,33,44)) # 用元組裝起來(lái) 
  2.  
  3. s4 

{11, 22, 33, 44}

集合的元素不能重復(fù)

集合中的元素是不能重復(fù)的;如果有重復(fù)的元素,集合會(huì)自動(dòng)去重。這是一種非常高效的去重方式

  1. s5 = set([1, 2, 3, 4, 3, 2, 1]) # 存在重復(fù)數(shù)據(jù) 
  2.  
  3. s5 

{1, 2, 3, 4}

產(chǎn)生的數(shù)據(jù)中自動(dòng)將重復(fù)的去掉了

  1. type(s5) # 查看類(lèi)型 

set

  1. s6 = set("javascript") # 字符串中a重復(fù)了,自動(dòng)去重 
  2. s6 

{'a', 'c', 'i', 'j', 'p', 'r', 's', 't', 'v'}

特別點(diǎn)

當(dāng)我們創(chuàng)建集合的時(shí)候,需要注意數(shù)據(jù)類(lèi)型

  1. s7 = {"python", [1,2,3,"java"], {"name":"xiaoming","age":19},100} 
  2.  
  3. s7 
  1. TypeError                                 Traceback (most recent call last
  2.  
  3. <ipython-input-11-b8ed1637ec12> in <module> 
  4. ----> 1 s7 = {"python", [1,2,3,"java"], {"name":"xiaoming","age":19},100} 
  5.       2 s7 
  6.  
  7.  
  8. TypeError: unhashable type: 'list' 

上面報(bào)錯(cuò)中的關(guān)鍵詞:unhashable,中文是不可哈希的。意思是創(chuàng)建的時(shí)候存在不可哈希的數(shù)據(jù)類(lèi)型:列表 。我們可以記?。?/p>

  • 不可哈希,即代表可變,比如列表、字典等
  • 可哈希,即代表不可變,比如字符串,字典的鍵等

當(dāng)我們創(chuàng)建集合的時(shí)候,元素必須是可哈希的

set集合方法

首先我們通過(guò)dir(set)來(lái)查看集合的操作方法:

  1. print(dir(set)) 

['__and__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__iand__', '__init__', '__init_subclass__', '__ior__', '__isub__', '__iter__', '__ixor__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__or__', '__rand__', '__reduce__', '__reduce_ex__', '__repr__', '__ror__', '__rsub__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__xor__', 'add', 'clear', 'copy', 'difference', 'difference_update', 'discard', 'intersection', 'intersection_update', 'isdisjoint', 'issubset', 'issuperset', 'pop', 'remove', 'symmetric_difference', 'symmetric_difference_update', 'union', 'update']

add-添加不可變?cè)?/h3>

集合中添加元素

  1. s3 # 原集合 

{6, 7, 8, 9}

  1. s3.add(1) # 添加1 
  1. s3 

{1, 6, 7, 8, 9}

  1. s3.add(2) # 添加2 
  1. s3 

{1, 2, 6, 7, 8, 9}

  1. s3.add([1,3,5]) 

---------------------------------------------------------------------------

  1. TypeError Traceback (most recent call last
  2.  
  3. in 
    1. s3.add(tuple1) # 添加元組 
  4.  
  5. ----> 1 s3.add([1,3,5]) 
  6.  
  7. TypeError: unhashable type: 'list' 

報(bào)錯(cuò)提示:列表是不可哈希,也就是可變類(lèi)型的。之前我們說(shuō)過(guò):集合中的元素都是可哈希(不可變類(lèi)型),所以不能直接添加

  1. list1 = [1,3,5] 
  2.  
  3. tuple1 = tuple(list1) # 列表轉(zhuǎn)成元組,元組是不可變的 
  4.  
  5. tuple1 

(1, 3, 5)

  1. s3.add(tuple1)  # 添加元組 
  1. s3 

{(1, 3, 5), 1, 2, 6, 7, 8, 9}

update-更新集合

更新集合中的元素,將兩個(gè)集合中的元素組合在一起

  1. # 創(chuàng)建兩個(gè)集合,有相同的元素“python” 
  2.  
  3. s8 = set(["python","java","c"]) 
  4. s9 = set(["python","go","javascript","html"]) 
  1. s8.update(s9) 
  1. s8 

{'c', 'go', 'html', 'java', 'javascript', 'python'}

生成的數(shù)據(jù)中自動(dòng)將python去重了

  1. s9 # s9還是沒(méi)有變化的 

{'go', 'html', 'javascript', 'python'}

update的參數(shù)不僅僅是集合,它的參數(shù)是不可變數(shù)據(jù)類(lèi)型:

  1. help(set.update) # 查看方法的文檔信息 

Help on method_descriptor:

update(...)

Update a set with the union of itself and others.

  1. s9.update("hello"
  1. s9 

{'e', 'go', 'h', 'html', 'javascript', 'l', 'o', 'python'}

  1. s9.update((7,8,9)) 
  1. s9 

{7, 8, 9, 'e', 'go', 'h', 'html', 'javascript', 'l', 'o', 'python'}

pop-隨機(jī)刪除

隨機(jī)刪除一個(gè)元素,并且返回刪除的結(jié)果。pop不能指定參數(shù),也就是不能指定想要?jiǎng)h除的元素

  1. s9.pop() 

'python'

  1. s9.pop() 

'html'

  1. s9.pop("python") # 不能帶參數(shù) 

---------------------------------------------------------------------------

TypeError Traceback (most recent call last)

in

----> 1 s9.pop("python") # 不能帶參數(shù)

TypeError: pop() takes no arguments (1 given)

remove-指定刪除

刪除的元素必須在集合中。如果不存在,則會(huì)報(bào)錯(cuò)

  1. s8 

{'c', 'go', 'html', 'java', 'javascript', 'python'}

  1. s8.remove("go"
  1. s8 # 結(jié)果顯示go被刪除了 

{'c', 'html', 'java', 'javascript', 'python'}

  1. s8.remove("go") # 再次刪除go就會(huì)報(bào)錯(cuò),因?yàn)間o已經(jīng)不存在了 

---------------------------------------------------------------------------

KeyError Traceback (most recent call last)

in

----> 1 s8.remove("go") # 再次刪除go就會(huì)報(bào)錯(cuò),因?yàn)間o已經(jīng)不存在了

KeyError: 'go'

discard-指定刪除

指定刪除某個(gè)元素,如果元素不存在,也不會(huì)報(bào)錯(cuò)。

  1. s8 # 原數(shù)據(jù) 

{'c', 'html', 'java', 'javascript', 'python'}

  1. s8.discard("html"
  1. s8 # 刪除后的數(shù)據(jù) 

{'c', 'java', 'javascript', 'python'}

  1. s8 

{'c', 'java', 'javascript', 'python'}

  1. s8.discard("go"

上面的結(jié)果表明:如果刪除的元素不存在,也不會(huì)報(bào)錯(cuò)。這個(gè)是和remove不一樣的地方

clear-清空集合

刪除集合中的全部元素

  1. s8 

{'c', 'java', 'javascript', 'python'}

  1. s8.clear() # 清空了集合 
  1. s8 

set()

  1. bool(s8) # bool值為False 

False

不變的集合-frozenset()

上面通過(guò)set方法創(chuàng)建的集合,我們了解到:集合是可變的,也就是可修改的,或者說(shuō)不可哈希的。

實(shí)際上還有一種方式創(chuàng)建的集合是不可變的:frozenset(),可以理解成凍集合,所以就不能進(jìn)行修改等操作啦。

  1. f_set = frozenset("python"
  2.  
  3. f_set 

frozenset({'h', 'n', 'o', 'p', 't', 'y'})

我們查看下這個(gè)凍集合的操作方法

  1. print(dir(f_set)) # 凍集合 

['__and__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__or__', '__rand__', '__reduce__', '__reduce_ex__', '__repr__', '__ror__', '__rsub__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__xor__', 'copy', 'difference', 'intersection', 'isdisjoint', 'issubset', 'issuperset', 'symmetric_difference', 'union']

  1. print(dir(s9)) # set集合,非凍集合 

['__and__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__iand__', '__init__', '__init_subclass__', '__ior__', '__isub__', '__iter__', '__ixor__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__or__', '__rand__', '__reduce__', '__reduce_ex__', '__repr__', '__ror__', '__rsub__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__xor__', 'add', 'clear', 'copy', 'difference', 'difference_update', 'discard', 'intersection', 'intersection_update', 'isdisjoint', 'issubset', 'issuperset', 'pop', 'remove', 'symmetric_difference', 'symmetric_difference_update', 'union', 'update']

通過(guò)對(duì)比兩種集合的操作方法,我們發(fā)現(xiàn):凍集合中明顯是少了很多增加、刪除等方法,所以凍集合是不可變的

集合運(yùn)算

在這個(gè)小節(jié)中介紹的是集合中的各種運(yùn)算,比如:交集、并集、補(bǔ)集等

in-元素判斷

  1. s5 

{1, 2, 3, 4}

  1. in s5 

True

  1. in s5 

False

issubset-子集與issuperset-超集

A如果是B的子集,那么B就是A的超集;也就說(shuō)A的元素全部在B中

  1. s10 = {1,2}  # 創(chuàng)建一個(gè)新的集合 
  2. s10 

{1, 2}

  1. s10.issubset(s5) # s10是s5的子集 

True

  1. s5.issuperset(s10) # s5是s10的超集 

True

  1. s9 

{7, 8, 9, 'e', 'go', 'h', 'javascript', 'l', 'o'}

  1. s9.issubset(s5) # 很顯然s9不是s5的子集 

False

intersection-交集

求兩個(gè)集合的交集,使用intersection函數(shù)或者&

  1. print(s5) 
  2.  
  3. print(s10) 

{1, 2, 3, 4}

{1, 2}

  1. s5.intersection(s10) 

{1, 2}

  1. s5 & s10 

{1, 2}

union-并集

使用函數(shù)union或者|來(lái)表示兩個(gè)集合的并集,會(huì)生成一個(gè)新的對(duì)象

  1. print(s5) 
  2.  
  3. print(s9) 

{1, 2, 3, 4}

{'javascript', 'o', 7, 'l', 'go', 'h', 8, 9, 'e'}

  1. s11 = s5|s9 
  2. s11 

{1, 2, 3, 4, 7, 8, 9, 'e', 'go', 'h', 'javascript', 'l', 'o'}

  1. s5.union(s9) 

{1, 2, 3, 4, 7, 8, 9, 'e', 'go', 'h', 'javascript', 'l', 'o'}

difference-差集、補(bǔ)集

使用函數(shù)difference或者減號(hào)-

  1. print(s5) 
  2.  
  3. print(s10) 

{1, 2, 3, 4}

{1, 2}

  1. s5 - s10 

{3, 4}

  1. s5.difference(s10) 

{3, 4}

  1. s10 - s5 

set()

symmetric_difference-對(duì)稱(chēng)差集

使用函數(shù)symmetric_difference或者symmetric_difference_update(原地更新數(shù)據(jù))

  1. s12 = {1,3,4,5,7} 
  2.  
  3. s12 

{1, 3, 4, 5, 7}

  1. s5 # 原數(shù)據(jù) 

{1, 2, 3, 4}

  1. s5.symmetric_difference(s12) 

{2, 5, 7}

  1. s5 # 原數(shù)據(jù)沒(méi)有改變 

{1, 2, 3, 4}

  1. s5.symmetric_difference_update(s12) 
  1. s5 # 原數(shù)據(jù)為輸出結(jié)果 

 

{2, 5, 7}

 

責(zé)任編輯:武曉燕 來(lái)源: 尤而小屋
相關(guān)推薦

2017-05-19 12:00:25

Python數(shù)據(jù)類(lèi)型集合

2021-10-12 13:35:30

C++Set紅黑樹(shù)

2022-03-24 07:38:07

注解SpringBoot項(xiàng)目

2020-12-18 08:03:00

插件MyBatis Executor

2019-11-14 09:53:30

Set集合存儲(chǔ)

2012-03-15 11:21:19

Java

2020-06-15 11:04:38

JavaScript 代碼JavaScript

2009-07-08 13:22:30

JDK源碼分析Set

2020-02-05 09:39:08

BashLinux命令

2017-03-14 14:38:21

數(shù)據(jù)庫(kù)SQL語(yǔ)句集合運(yùn)算

2019-04-15 08:49:59

阿里巴巴容量集合

2019-08-01 12:56:00

Python代碼記錄

2009-12-21 15:33:07

WCF集合元素

2009-10-26 12:17:03

linux腳本編寫(xiě)

2017-11-16 09:28:04

2023-12-01 11:13:50

JavaTreeSet

2018-02-27 11:00:56

2021-10-26 11:45:22

Vue面試前端

2022-11-01 07:54:18

Python工具類(lèi)計(jì)數(shù)器

2016-08-01 16:26:34

ES6集合
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)