新聞中心
DICT常用操作

創(chuàng)新互聯(lián)2013年至今,先為金寨等服務建站,金寨等地企業(yè),進行企業(yè)商務咨詢服務。為金寨企業(yè)網(wǎng)站制作PC+手機+微官網(wǎng)三網(wǎng)同步一站式服務解決您的所有建站問題。
引言
clear(): 清空字典
copy(): 返回一個淺拷貝
fromkeys(): 將可迭代對象中的每一個元素作為key和同一個value拼成字典
get(): 根據(jù)key返回value,若無對應的鍵值對,則返回None,也可以指定默認返回值,和索引訪問相比,不會產(chǎn)生異常。
items():返回一個dict_items類型,支持迭代,鍵值對以元組形式組織
SETdefault(): 獲取key對應的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).
當前標題:創(chuàng)新互聯(lián)Python教程:深入理解Python的set和dict
當前網(wǎng)址:http://www.dlmjj.cn/article/djhiidi.html


咨詢
建站咨詢
