集合
基本定義:通過{}
構(gòu)建
特性:無序,不可重復(fù),元素可以是不同類型(不支持unhashable 類型的元素)
基礎(chǔ)操作
-
集合運(yùn)算
1.1|
并集運(yùn)算符:求兩個集合并或合集
1.2&
交集運(yùn)算符:求兩個集合交集
1.3-
差集運(yùn)算符:求兩個集合差集s1 = {1, 2, 3, 4, 5, 6} s2 = {4, 5, 6, 7, 8, 9} print("s1: {}".format(s1)) print("s2: {}".format(s2)) # 并集 s = s1 | s2 print("s1|s2: {}".format(s)) # 交集 s = s1 & s2 print("s1 & s2: {}".format(s)) # 差集 s = s1 - s2 print("s1 - s2: {}".format(s)) # 差集 s = s2 - s1 print("s2 - s1: {}".format(s)) 執(zhí)行結(jié)果: s1: {1, 2, 3, 4, 5, 6} s2: {4, 5, 6, 7, 8, 9} s1|s2: {1, 2, 3, 4, 5, 6, 7, 8, 9} s1 & s2: {4, 5, 6} s1 - s2: {1, 2, 3} s2 - s1: {8, 9, 7}
-
集合操作
集合只存在添加和刪除兩個操作,無所謂修改操作
2.1 添加
set.add(x)——將x添加到集合中
2.2 刪除
set.remove(x)——從集合中移除元素 x。 如果 x 不存在于集合中則會引發(fā) KeyError致扯。
set.discard(x)——如果元素 x 存在于集合中則將其移除训挡。
set.pop()——從集合中移除并返回任意一個元素尚镰。 如果集合為空則會引發(fā) KeyError。任意代表隨機(jī)嗎立倍?灭红!
set.clear()——清空集合# 添加 s = {1,2,3,4,5} print("s:{}".format(s)) s.add(6) print("s:{}".format(s)) s.add(3) print("s:{}".format(s)) print("*" * 23) # 刪除 # remove() s.remove(4) print("s:{}".format(s)) # s.remove(4) # Traceback (most recent call last): # File "XXXXXXX", line XXX, in <module> # s.remove(4) # KeyError: 4 # discard() returntest = s.discard(5) print("returntest:{}".format(returntest)) print("s:{}".format(s)) s.discard(5) # 不拋異常 # pop() s.pop() print("s:{}".format(s)) s.pop() print("s:{}".format(s)) s.pop() print("s:{}".format(s)) s.pop() print("s:{}".format(s)) # s.pop() # print("s:{}".format(s)) # Traceback (most recent call last): # File "d:/Dev/WorkSpace/01SunnyLearn/Python/Basic/SunnyPython/basic/02group.py", line 620, in <module> # s.pop() # KeyError: 'pop from an empty set' # All Test hello = "Hello Python World! We Are Family" for char in hello: s.add(char) print("s:{}".format(s)) spop = s.pop() print("spop:{}".format(spop)) print("s:{}".format(s)) spop = s.pop() print("spop:{}".format(spop)) print("s:{}".format(s)) spop = s.pop() print("spop:{}".format(spop)) print("s:{}".format(s)) s.clear() print("s:{}".format(s)) 執(zhí)行結(jié)果: s:{1, 2, 3, 4, 5} s:{1, 2, 3, 4, 5, 6} s:{1, 2, 3, 4, 5, 6} *********************** s:{1, 2, 3, 5, 6} returntest:None s:{1, 2, 3, 6} s:{2, 3, 6} s:{3, 6} s:{6} s:set() s:{'r', 'A', 'd', 'n', 'H', 't', 'm', ' ', 'h', 'P', 'l', 'e', 'W', 'F', 'a', 'y', '!', 'i', 'o'} spop:A s:{'r', 'd', 'n', 'H', 't', 'm', ' ', 'h', 'P', 'l', 'e', 'W', 'F', 'a', 'y', '!', 'i', 'o'} spop:d s:{'r', 'n', 'H', 't', 'm', ' ', 'h', 'P', 'l', 'e', 'W', 'F', 'a', 'y', '!', 'i', 'o'} spop:n s:{'r', 'H', 't', 'm', ' ', 'h', 'P', 'l', 'e', 'W', 'F', 'a', 'y', '!', 'i', 'o'} s:set()
-
其他操作
3.1 len() 集合大小
3.2 in, not in 成員判斷符s = "Hello Python World! We are Family!" print("s:{}".format(s)) print("s字符串列表長度:{}".format(len(s))) t = set() for char in s: t.add(char) print("t:{}".format(t)) print("t大小:{}".format(len(t))) print("{}".format("H" in t)) print("{}".format("H" not in t)) print("{}".format("U" in t )) print("{}".format("U" not in t )) 執(zhí)行結(jié)果: s:Hello Python World! We are Family! s字符串列表長度:34 t:{'r', 'm', 'i', 'H', 'y', 'W', '!', 'F', ' ', 'd', 'a', 'o', 'l', 'P', 'h', 'e', 'n', 't'} t大小:18 True False False True
補(bǔ)充
- 如何定義空集合
{}
其實是定義了一個空字典口注;定義空集合需要使用set()
- 集合無序性
作為一種無序的多項集变擒,集合并不記錄元素位置或插入順序。 相應(yīng)地寝志,集合不支持索引娇斑、切片或其他序列類的操作
QA
Q1:為什么集合不支持unhashable 類型的元素
A:
簡單的可以理解為可哈希其實就是不可變,只有哈希不可變才能比較確認(rèn)是否重復(fù)材部,才能實現(xiàn)集合的無重復(fù)特性哦:晾隆!乐导!集合在內(nèi)部需要使用哈希值來判斷是否相等?喽 !物臂!
-
hashable -- 可哈希
一個對象的哈希值如果在其生命周期內(nèi)絕不改變旺拉,就被稱為 可哈希 (它需要具有__hash__()
方法),并可以同其他對象進(jìn)行比較(它需要具有__eq__()
方法)棵磷《旯罚可哈希對象必須具有相同的哈希值,比較結(jié)果才會相同仪媒。沉桌,可哈希性使得對象能夠作為字典鍵或集合成員使用,因為這些數(shù)據(jù)結(jié)構(gòu)要在內(nèi)部使用哈希值。
大多數(shù) Python 中的不可變內(nèi)置對象都是可哈希的蒲牧;可變?nèi)萜鳎ɡ缌斜砘蜃值洌┒疾豢晒F埠兀徊豢勺內(nèi)萜鳎ɡ缭M和 frozenset)僅當(dāng)它們的元素均為可哈希時才是可哈希的。 用戶定義類的實例對象默認(rèn)是可哈希的冰抢。 它們在比較時一定不相同(除非是與自己比較)松嘶,它們的哈希值的生成是基于它們的
id()
。內(nèi)置類型分類
hashable:int, float, decimal, complex, bool, str, tuple,
unhashable: list, dict, set
驗證方法:>>> type(str.__hash__) <class 'wrapper_descriptor'> >>> type(int.__hash__) <class 'wrapper_descriptor'> >>> type(float.__hash__) <class 'wrapper_descriptor'> >>> import decimal >>> type(decimal.__hash__) <class 'method-wrapper'> >>> type(complex.__hash__) <class 'wrapper_descriptor'> >>> type(bool.__hash__) <class 'wrapper_descriptor'> >>> type(tuple.__hash__) <class 'wrapper_descriptor'> >>> type(list.__hash__) <class 'NoneType'> >>> type(dict.__hash__) <class 'NoneType'> >>> type(set.__hash__) <class 'NoneType'>
hash方法
>>> hash(0)
0
>>> hash(23)
23
>>> hash(-23)
-23
>>> hash(23.24)
553402322211282967
>>> hash(-23.24)
-553402322211282967
>>> hash('23')
-4826980359952576689
>>> hash(23+24j)
24000095
>>> hash(23-24j)
-24000049
>>> hash(True)
1
>>> hash(False)
0
>>> hash(None)
124074573
>>> hash([1,2,3,4,5])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
>>> hash({'key1':1, 'key2':2})
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'dict'
>>> hash((1,2,3,4,5))
8315274433719620810
>>> hash((1,2,3,[4,5]))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
>>> hash((1,2,3,(4,5)))
-325972594757234431
>>> hash({1,2,3})
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'set'
Q2:set.pop()所謂任意的機(jī)制與原理
A: //TODO
https://stackoverflow.com/questions/21017188/set-pop-isnt-random
參考:
互聯(lián)網(wǎng)相關(guān)資料