集合和字典
上文說完了列表和元組,本文繼續(xù)介紹另外兩種常用的數(shù)據(jù)結(jié)構(gòu),集合和字典。
集合 set
集合是由不重復(fù)元素組成的無序容器。
Python中的集合和數(shù)學(xué)上的集合概念基本相同,也可以求交集、并集、差集等操作。
參考手冊:“set 對象是由具有唯一性的 hashable 對象所組成的無序多項(xiàng)集。”
集合的創(chuàng)建
創(chuàng)建集合用花括號或 set函數(shù)。更常見的是用集合推導(dǎo)式。
注意,創(chuàng)建空集合只能用 set(),不能用 {},{} 創(chuàng)建的是空字典。
集合創(chuàng)建方法:
使用花括號內(nèi)以逗號分隔元素的方式:
{'jack', 'sjoerd'}使用集合推導(dǎo)式:
{c for c in 'abracadabra' if c not in 'abc'}使用類型構(gòu)造器:
set(),set('foobar'),set(['a', 'b', 'foo'])
集合的應(yīng)用
集合具有不重復(fù)的性質(zhì),可以用來去重。
也可以用它的運(yùn)算差**a-b、交a & b、并a | b、對稱差**a ^ b。
注:對稱差,等價(jià)于(a | b) - (a&b),即a與b的并集減去a與b的交集。
basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
print(basket) # 重復(fù)元素被去除
'orange' in basket # 支持 in
'crabgrass' in basket
# 集合間的運(yùn)算:
a = set('abracadabra')
b = set('alacazam')
a # unique letters in a
a - b # letters in a but not in b
a | b # letters in a or b or both
a & b # letters in both a and b
a ^ b # letters in a or b but not both
frozenset 凍結(jié)的set:
frozenset 類型是不可變并且為 hashable --- 其內(nèi)容在被創(chuàng)建后不能再改變;因此它可以被用作字典的鍵或其他集合的元素。
fst = frozenset("abc")
字典 dict
字典比集合更常用,現(xiàn)實(shí)中很多東西都可以用字典表示,比如“通訊錄”、“日志記錄”。
字典可以理解為鍵值對的集合,如{'鴿子': 10001}。'鴿子': 10001 就是一個鍵值對。
'鴿子'是鍵,10001是對應(yīng)的值。
我們通過鍵查找值。 因此鍵必須是不可變類型,如字符串或數(shù)字,包含不可變對象的元組。列表不可以作為鍵,因?yàn)榱斜砜捎胊ppend()等方法修改。鍵也必須是唯一的。
字典的創(chuàng)建:
常用的方法:
使用花括號內(nèi)以逗號分隔
鍵: 值對的方式:{'jack': 4098, 'sjoerd': 4127}使用字典推導(dǎo)式:
{},{x: x ** 2 for x in range(10)}使用類型構(gòu)造器:
dict(),dict([('foo', 100), ('bar', 200)]),dict(foo=100, bar=200)
補(bǔ)充:使用類型構(gòu)造器dit()創(chuàng)建字典。
class dict(**kwargs) #字典
class dict(mapping, **kwargs) #從映射
class dict(iterable, **kwargs) #從可迭代對象,iterable中每個元素都是一對
#如:[('two', 2), ('one', 1), ('three',3)]
a = dict(one=1, two=2, three=3) #key=value
b = {'one': 1, 'two': 2, 'three': 3} #直接構(gòu)造
c = dict(zip(['one', 'two', 'three'], [1, 2, 3])) # 從映射
d = dict([('two', 2), ('one', 1), ('three', 3)]) #從iterable
e = dict({'three': 3, 'one': 1, 'two': 2}) # 從另一個dict
f = dict({'one': 1, 'three': 3}, two=2) # dict , key=value
a == b == c == d == e == f #這些方式創(chuàng)建的字典都等價(jià)
字典常用方法:
最常用的方法是通過鍵存儲讀取值。
tel = {'jack': 4098, 'sape': 4139} # 初始化
tel['guido'] = 412 # 存儲值
tel['jack'] # 訪問值
del tel['sape'] #刪除值
get(key[, default]) 更穩(wěn)健地讀取值。
如果 key 存在于字典中則返回 key 的值則返回 key 的值,否則返回 default。 如果 default 未給出則默認(rèn)為 None,因而此方法絕不會引發(fā) KeyError。
tel.get('jkl',0000) #jkl不在字典中時(shí)返回默認(rèn)值0000,不會引發(fā)KeyError
對字典執(zhí)行 list(d) 操作,返回該字典中所有鍵的列表,按插入次序排列。
檢查某個鍵是否在字典中,使用in
'guido' in tel
'jack' not in tel
遍歷字典
在字典中循環(huán)時(shí),用 items() 方法可同時(shí)取出鍵和對應(yīng)的值:
knights = {'gallahad': 'the pure', 'robin': 'the brave'}
for k, v in knights.items():
print(k, v)
更新字典
update([other])
使用來自 other 的鍵/值對更新字典,覆蓋原有的鍵。 返回 None。
update() 接受另一個字典對象,或者一個包含鍵/值對(二元組形式)的可迭代對象。 如果給出了關(guān)鍵字參數(shù),則會以其所指定的鍵/值對更新字典: d.update(red=1, blue=2)。
Counter
collections有很多擴(kuò)展的子類,可以去文檔的collections里找。
collections --- 容器數(shù)據(jù)類型 — Python 3.10.4 文檔
這里介紹一下常用的Counter,Counter是字典的一個子類,可以方便的統(tǒng)計(jì)次數(shù)。
from collections import Counter
cnt = Counter()
words = ['red', 'blue', 'red', 'green', 'blue', 'blue']
for word in words:
cnt[word] += 1
print(cnt) # Counter({'blue': 3, 'red': 2, 'green': 1})
# 更便捷的方法
cnt2 = Counter(words)
print(cnt2)
Counter對象有一個字典接口,如果引用的鍵沒有任何記錄,就返回一個0,而不是彈出一個 KeyError :
print(cnt['dark']) # 0
most_common([n])
返回一個列表,其中包含 n 個最常見的元素及出現(xiàn)次數(shù),按常見程度由高到低排序。
如果 n 被省略或?yàn)?None,most_common() 將返回計(jì)數(shù)器中的 所有 元素。
(計(jì)數(shù)值相等的元素按首次出現(xiàn)的順序排序):
Counter('abracadabra').most_common(3)
Counter常用案例:
c.total() # 所有元素的計(jì)數(shù)總和
c.clear() # reset all counts
list(c) # list unique elements
set(c) # convert to a set
dict(c) # convert to a regular dictionary
c.items() # convert to a list of (elem, cnt) pairs
Counter(dict(list_of_pairs)) # convert from a list of (elem, cnt) pairs
c.most_common()[:-n-1:-1] # n least common elements
+c # remove zero and negative counts