python入门系列:深入Python的set和dict
dict常用操作
引言
clear(): 清空字典
copy(): 返回一個淺拷貝
fromkeys(): 將可迭代對象中的每一個元素作為key和同一個value拼成字典
get(): 根據key返回value,若無對應的鍵值對,則返回None,也可以指定默認返回值,和索引訪問相比,不會產生異常。
items():返回一個dict_items類型,支持迭代,鍵值對以元組形式組織
setdefault(): 獲取key對應的value值,先調用get(),若不存在該鍵值對,則添加
update(): 合并字典,或鍵值對元組構成的可迭代對象
使用案例
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:
<class 'dict_items'>
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) 來構建出可變集合對象
通過 frozenset(Iterable) 構建不可變集合對象
"""
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的實現原理
引言
dict和set的查找性能遠遠大于list
dict和set底層通過散列表存儲,因此也要求dict的key是可哈希的,不可變對象都是可哈希的
哈希的原理
以字典為例
存儲之前要通過哈希函數來計算key的值,得到存儲索引,如果得到的結果已經被使用,要處理沖突,重新計算后再進行存儲
自定義的類通過實現hash(),就可以存儲在dict和set中
因此,具體的存儲順序和元素添加的順序可能有關
注:喜歡python + qun:839383765 可以獲取Python各類免費最新入門學習資料!
轉載于:https://blog.51cto.com/14186420/2349824
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的python入门系列:深入Python的set和dict的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: IBM开放Watson AI服务增加云服
- 下一篇: websocket python爬虫_p