python入門系列:深入Python的set和dict

dict常用操作

引言

clear(): 清空字典

copy(): 返回一個淺拷貝

fromkeys(): 將可迭代對象中的每一個元素作為key和同一個value拼成字典

get(): 根據(jù)key返回value,若無對應(yīng)的鍵值對,則返回None,也可以指定默認返回值,和索引訪問相比,不會產(chǎn)生異常。

items():返回一個dict_items類型,支持迭代,鍵值對以元組形式組織

setdefault(): 獲取key對應(yīng)的value值,先調(diào)用get(),若不存在該鍵值對,則添加

update(): 合并字典,或鍵值對元組構(gòu)成的可迭代對象

使用案例

# 1. clear()

d = {name:"MetaTian", age:"22"}

d.clear()

# 2. copy()

new_dict = d.copy()

new_dict["age"] = 18

print(new_dict)

print(d)

# resutl:

# {'age': 18, 'name': 'MetaTian'}

# {'age': '22', 'name': 'MetaTian'}

# 3. fromkeys()

d = dict.fromkeys(range(3), "MetaTian")

print(d)

# result:

# {0: 'MetaTian', 1: 'MetaTian', 2: 'MetaTian'}

# 4. get()

print(d.get(2))

print(d.get(3))

print(d.get(3, "null"))

# result:

# MetaTian

# None

# null

# 5. items()

print(type(d.items()))

print(d.items())

# result:

#

# dict_items([(0, 'MetaTian'), (1, 'MetaTian'), (2, 'MetaTian')])

# 6. setdefault()

d = {}

value = d.setdefault("name", "MetaTian") # 如果無 name 這個 key,則添加

print(value, d)

# result:

# MetaTian {'name': 'MetaTian'}

# 7. update()

d1 = {1:"a"}

d2 = {2:"b"}

d1.update(d2)

d2.update([(3, "c"), (4, "d")])

print(d1)

print(d2)

# result:

# {1: 'a', 2: 'b'}

# {2: 'b', 3: 'c', 4: 'd'}

set和frozenset

引言

set是可變集合,frozenset是不可變集合

集合中的元素無序,不重復

使用案例

"""

通過 set(Iterable) 來構(gòu)建出可變集合對象

通過 frozenset(Iterable) 構(gòu)建不可變集合對象

"""

s = set("12345666")

fs = frozenset(['a', 'b', 'c', 'a']) # 不可變類型,可以作為 dict 的 key

print(s)

print(fs)

# result:

# {'6', '1', '4', '5', '3', '2'}

# frozenset({'b', 'a', 'c'})

"""

向 set 中添加元素

add()

update()

"""

s1, s2 = set("123"), set("234")

s1.update(s2)

s2.add('5')

print(s1)

print(s2)

# result:

# {'1', '2', '3', '4'}

# {'2', '3', '5', '4'}

"""

集合的運算

- 差

& 交

| 并

"""

s1, s2 = set("123"), set("234")

print(s1 - s2)

print(s1 & s2)

print(s1 | s2)

# result:

# {'1'}

# {'2', '3'}

# {'3', '1', '2', '4'}

dict和set的實現(xiàn)原理

引言

dict和set的查找性能遠遠大于list

dict和set底層通過散列表存儲,因此也要求dict的key是可哈希的,不可變對象都是可哈希的

哈希的原理

以字典為例

存儲之前要通過哈希函數(shù)來計算key的值,得到存儲索引,如果得到的結(jié)果已經(jīng)被使用,要處理沖突,重新計算后再進行存儲

自定義的類通過實現(xiàn)__hash__(),就可以存儲在dict和set中

因此,具體的存儲順序和元素添加的順序可能有關(guān)

注:喜歡python + qun:839383765 可以獲取Python各類免費最新入門學習資料!

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容