簡(jiǎn)介
2.4新增
源代碼:Lib/collections.py and Lib/_abcoll.py
提供了替換dict, list, set和tuple的數(shù)據(jù)類(lèi)型。
主要類(lèi)型如下:
- namedtuple(): 命名元組包帚,創(chuàng)建有名字域的元組子類(lèi)的工廠函數(shù)贡必。python 2.6新增剧防。
- deque:雙端隊(duì)列劈榨,類(lèi)似于列表浙炼,兩端進(jìn)棧和出棧都比較快速。python 2.4新增土童。
- Counter:字典的子類(lèi),用于統(tǒng)計(jì)哈希對(duì)象工坊。python 2.7新增献汗。
- OrderedDict:有序字典,字典的子類(lèi)王污,記錄了添加順序罢吃。python 2.7新增。
- defaultdict:dict的子類(lèi)昭齐,調(diào)用一個(gè)工廠函數(shù)支持不存在的值尿招。python 2.5新增。
還提供了抽象基類(lèi)阱驾,用來(lái)測(cè)試類(lèi)是否提供了特殊接口就谜,不管是哈希或者映射里覆。
Counter
計(jì)數(shù)器(Counter)是一個(gè)容器丧荐,用來(lái)跟蹤值出現(xiàn)了多少次。和其他語(yǔ)言中的bag或multiset類(lèi)似喧枷。
計(jì)數(shù)器支持三種形式的初始化虹统。構(gòu)造函數(shù)可以調(diào)用序列弓坞,包含key和計(jì)數(shù)的字典,或使用關(guān)鍵字參數(shù)车荔。
import collections
print(collections.Counter(['a', 'b', 'c', 'a', 'b', 'b']))
print(collections.Counter({'a': 2, 'b': 3, 'c': 1}))
print(collections.Counter(a=2, b=3, c=1))
執(zhí)行結(jié)果:
$ python3 collections_counter_init.py
Counter({'b': 3, 'a': 2, 'c': 1})
Counter({'b': 3, 'a': 2, 'c': 1})
Counter({'b': 3, 'a': 2, 'c': 1})
注意key的出現(xiàn)順序是根據(jù)計(jì)數(shù)的從大到小渡冻。
可以創(chuàng)建空的計(jì)數(shù)器,再u(mài)pdate:
import collections
c = collections.Counter()
print('Initial :{0}'.format(c))
c.update('abcdaab')
print('Sequence:{0}'.format(c))
c.update({'a': 1, 'd': 5})
print('Dict :{0}'.format(c))
執(zhí)行結(jié)果:
python3.5 collections_counter_update.py*
Initial :Counter()
Sequence:Counter({'a': 3, 'b': 2, 'c': 1, 'd': 1})
Dict :Counter({'d': 6, 'a': 4, 'b': 2, 'c': 1})
訪問(wèn)計(jì)數(shù)
import collections
c = collections.Counter('abcdaab')
for letter in 'abcde':
print('{0} : {1}'.format(letter, c[letter]))
執(zhí)行結(jié)果:
$ python3.5 collections_counter_get_values.py
a : 3
b : 2
c : 1
d : 1
e : 0
注意這里不存在的元素也會(huì)統(tǒng)計(jì)為0忧便。
elements方法可以列出所有元素:
import collections
c = collections.Counter('extremely')
c['z'] = 0
print(c)
print(list(c.elements()))
執(zhí)行結(jié)果:
$ python3.5 collections_counter_elements.py
Counter({'e': 3, 'y': 1, 'r': 1, 'x': 1, 'm': 1, 'l': 1, 't': 1, 'z': 0})
['y', 'r', 'x', 'm', 'l', 't', 'e', 'e', 'e']
注意后面并沒(méi)有輸出計(jì)數(shù)為0的元素族吻。
most_common()可以提取出最常用的元素。
import collections
c = collections.Counter()
with open('/etc/adduser.conf', 'rt') as f:
for line in f:
c.update(line.rstrip().lower())
print('Most common:')
for letter, count in c.most_common(3):
print('{0}: {1}'.format(letter, count))
執(zhí)行結(jié)果:
$ python3.5 collections_counter_most_common.py
Most common:
: 401
e: 310
s: 221
Counter還支持算術(shù)和集合運(yùn)算茬腿,它們都只會(huì)保留數(shù)值為正整數(shù)的key呼奢。
import collections
import pprint
c1 = collections.Counter(['a', 'b', 'c', 'a', 'b', 'b'])
c2 = collections.Counter('alphabet')
print('C1:')
pprint.pprint(c1)
print('C2:')
pprint.pprint(c2)
print('\nCombined counts:')
print(c1 + c2)
print('\nSubtraction:')
print(c1 - c2)
print('\nIntersection (taking positive minimums):')
print(c1 & c2)
print('\nUnion (taking maximums):')
print(c1 | c2)
執(zhí)行結(jié)果:
$ python3 collections_counter_arithmetic.py
C1:
Counter({'b': 3, 'a': 2, 'c': 1})
C2:
Counter({'a': 2, 't': 1, 'l': 1, 'e': 1, 'b': 1, 'p': 1, 'h': 1})
Combined counts:
Counter({'b': 4, 'a': 4, 'p': 1, 'e': 1, 'c': 1, 't': 1, 'l': 1, 'h': 1})
Subtraction:
Counter({'b': 2, 'c': 1})
Intersection (taking positive minimums):
Counter({'a': 2, 'b': 1})
Union (taking maximums):
Counter({'b': 3, 'a': 2, 'p': 1, 'e': 1, 'c': 1, 't': 1, 'l': 1, 'h': 1})
上面的例子讓人覺(jué)得collections只能處理單個(gè)字符。其實(shí)不是這樣的切平,請(qǐng)看標(biāo)準(zhǔn)庫(kù)中的實(shí)例握础。
from collections import Counter
import pprint
import re
cnt = Counter()
for word in ['red', 'blue', 'red', 'green', 'blue', 'blue']:
cnt[word] += 1
pprint.pprint(cnt)
cnt = Counter(['red', 'blue', 'red', 'green', 'blue', 'blue'])
pprint.pprint(cnt)
words = re.findall('\w+', open('/etc/adduser.conf').read().lower())
print(Counter(words).most_common(10))
執(zhí)行結(jié)果:
$ python3 collections_counter_normal.py
Counter({'blue': 3, 'red': 2, 'green': 1})
Counter({'blue': 3, 'red': 2, 'green': 1})
[('the', 27), ('is', 13), ('be', 12), ('if', 12), ('will', 12), ('user', 10), ('home', 9), ('default', 9), ('to', 9), ('users', 8)]
第1段代碼和第2段的代碼效果式樣的,后面一段代碼通過(guò)Counter實(shí)現(xiàn)了簡(jiǎn)單的單詞的統(tǒng)計(jì)功能悴品。比如面試題:使用python打印出/etc/ssh/sshd_config出現(xiàn)次數(shù)最高的10個(gè)單詞及其出現(xiàn)次數(shù)禀综。
下面看看Counter的相關(guān)定義:
class collections.Counter([iterable-or-mapping]) 。注意Counter是無(wú)序的字典苔严。在key不存在的時(shí)候返回0. c['sausage'] = 0定枷。設(shè)置值為0不會(huì)刪除元素,要使用del c['sausage']届氢。
除了標(biāo)準(zhǔn)的字典方法欠窒,額外增加了:
elements() :返回一個(gè)包含所有元素的迭代器,忽略小于1的計(jì)數(shù)退子。
most_common([n]):返回最常用的元素及其計(jì)數(shù)的列表岖妄。默認(rèn)返回所有元素。
subtract([iterable-or-mapping]) :相減寂祥。
namedtuple
命名元組和普通元組的的內(nèi)存效率差不多荐虐。它不會(huì)針對(duì)每個(gè)實(shí)例生成字典。
import collections
Person = collections.namedtuple('Person', 'name age gender')
print('Type of Person:{0}'.format(type(Person)))
bob = Person(name='Bob', age=30, gender='male')
print('\nRepresentation: {0}'.format(bob))
jane = Person(name='Jane', age=29, gender='female')
print('\nField by name: {0}'.format(jane.name))
print('\nFields by index:')
for p in [bob, jane]:
print('{0} is a {1} year old {2}'.format(*p))
執(zhí)行結(jié)果:
$ python3 collections_namedtuple_person.py
Type of Person:<class 'type'>
Representation: Person(name='Bob', age=30, gender='male')
Field by name: Jane
Fields by index:
Bob is a 30 year old male
Jane is a 29 year old female
從上例可以看出命名元組Person類(lèi)和excel的表頭類(lèi)似丸凭,給下面的每個(gè)列取個(gè)名字福扬,真正excel行數(shù)據(jù)則存儲(chǔ)在Person類(lèi)的實(shí)例中。好處在于可以jane.name這樣的形式訪問(wèn)惜犀,比記元組的index要直觀铛碑。
注意列名在實(shí)現(xiàn)內(nèi)部其實(shí)是個(gè)標(biāo)識(shí)符,所以不能和關(guān)鍵字沖突虽界,只能用字母或者下劃線開(kāi)頭亚茬。下例會(huì)報(bào)錯(cuò):
import collections
try:
collections.namedtuple('Person', 'name class age gender')
except ValueError as err:
print(err)
try:
collections.namedtuple('Person', 'name age gender age')
except ValueError as err:
print(err)
執(zhí)行結(jié)果:
$ python3 collections_namedtuple_bad_fields.py
Type names and field names cannot be a keyword: 'class'
Encountered duplicate field name: 'age'
設(shè)置rename=True,列名會(huì)在沖突時(shí)自動(dòng)重命名浓恳,不過(guò)這種重命名并不美觀刹缝。
import collections
with_class = collections.namedtuple('Person', 'name class age gender',
rename=True)
print(with_class._fields)
two_ages = collections.namedtuple('Person', 'name age gender age',
rename=True)
print(two_ages._fields)
執(zhí)行結(jié)果:
$ python collections_namedtuple_rename.py
('name', '_1', 'age', 'gender')
('name', 'age', 'gender', '_3')
- 定義
collections.namedtuple(typename, field_names[, verbose=False][, rename=False]) 返回一個(gè)命名元組類(lèi)碗暗。如果verbose為T(mén)rue,會(huì)打印類(lèi)定義信息
命名元組在處理數(shù)據(jù)庫(kù)的時(shí)候比較有用:
ChainMap 映射鏈
用于查找多個(gè)字典梢夯。
ChainMap管理一系列字典言疗,按順序根據(jù)key查找值。
- 訪問(wèn)值:
API和字典類(lèi)似颂砸。
collections_chainmap_read.py
import collections
a = {'a': 'A', 'c': 'C'}
b = {'b': 'B', 'c': 'D'}
m = collections.ChainMap(a, b)
print('Individual Values')
print('a = {}'.format(m['a']))
print('b = {}'.format(m['b']))
print('c = {}'.format(m['c']))
print()
print('m = {}'.format(m))
print('Keys = {}'.format(list(m.keys())))
print('Values = {}'.format(list(m.values())))
print()
print('Items:')
for k, v in m.items():
print('{} = {}'.format(k, v))
print()
print('"d" in m: {}'.format(('d' in m)))
執(zhí)行結(jié)果:
$ python3 collections_chainmap_read.py
Individual Values
a = A
b = B
c = C
m = ChainMap({'c': 'C', 'a': 'A'}, {'c': 'D', 'b': 'B'})
Keys = ['c', 'a', 'b']
Values = ['C', 'A', 'B']
Items:
c = C
a = A
b = B
"d" in m: False
- 調(diào)整順序
collections_chainmap_reorder.py
import collections
a = {'a': 'A', 'c': 'C'}
b = {'b': 'B', 'c': 'D'}
m = collections.ChainMap(a, b)
print(m.maps)
print('c = {}\n'.format(m['c']))
# reverse the list
m.maps = list(reversed(m.maps))
print(m.maps)
print('c = {}'.format(m['c']))
執(zhí)行結(jié)果:
$ python3 collections_chainmap_reorder.py
[{'c': 'C', 'a': 'A'}, {'c': 'D', 'b': 'B'}]
c = C
[{'c': 'D', 'b': 'B'}, {'c': 'C', 'a': 'A'}]
c = D
- 更新值
更新原字典:
collections_chainmap_update_behind.py
import collections
a = {'a': 'A', 'c': 'C'}
b = {'b': 'B', 'c': 'D'}
m = collections.ChainMap(a, b)
print('Before: {}'.format(m['c']))
a['c'] = 'E'
print('After : {}'.format(m['c']))
執(zhí)行結(jié)果
$ python3 collections_chainmap_update_behind.py
Before: C
After : E
直接更新ChainMap:
collections_chainmap_update_directly.py
import collections
a = {'a': 'A', 'c': 'C'}
b = {'b': 'B', 'c': 'D'}
m = collections.ChainMap(a, b)
print('Before:', m)
m['c'] = 'E'
print('After :', m)
print('a:', a)
執(zhí)行結(jié)果
$ python3 collections_chainmap_update_directly.py
Before: ChainMap({'c': 'C', 'a': 'A'}, {'c': 'D', 'b': 'B'})
After : ChainMap({'c': 'E', 'a': 'A'}, {'c': 'D', 'b': 'B'})
a: {'c': 'E', 'a': 'A'}
ChainMap可以方便地在前面插入字典噪奄,這樣可以避免修改原來(lái)的字典。
collections_chainmap_new_child.py
import collections
a = {'a': 'A', 'c': 'C'}
b = {'b': 'B', 'c': 'D'}
m1 = collections.ChainMap(a, b)
m2 = m1.new_child()
print('m1 before:', m1)
print('m2 before:', m2)
m2['c'] = 'E'
print('m1 after:', m1)
print('m2 after:', m2)
執(zhí)行結(jié)果
$ python3 collections_chainmap_new_child.py
m1 before: ChainMap({'a': 'A', 'c': 'C'}, {'b': 'B', 'c': 'D'})
m2 before: ChainMap({}, {'a': 'A', 'c': 'C'}, {'b': 'B', 'c': 'D'})
m1 after: ChainMap({'a': 'A', 'c': 'C'}, {'b': 'B', 'c': 'D'})
m2 after: ChainMap({'c': 'E'}, {'a': 'A', 'c': 'C'}, {'b': 'B', 'c': 'D'})
還可以通過(guò)傳入字典的方式
collections_chainmap_new_child_explicit.py
import collections
a = {'a': 'A', 'c': 'C'}
b = {'b': 'B', 'c': 'D'}
c = {'c': 'E'}
m1 = collections.ChainMap(a, b)
m2 = m1.new_child(c)
print('m1["c"] = {}'.format(m1['c']))
print('m2["c"] = {}'.format(m2['c']))
執(zhí)行結(jié)果
$ python3 collections_chainmap_new_child_explicit.py
m1["c"] = C
m2["c"] = E
另外一種等價(jià)的方式:
m2 = collections.ChainMap(c, *m1.maps)
參考資料
- python測(cè)試等IT技術(shù)支持qq群: 144081101(后期會(huì)錄制視頻存在該群群文件) 591302926 567351477 釘釘免費(fèi)群:21745728
- 本文最新版本地址
- 本文涉及的python測(cè)試開(kāi)發(fā)庫(kù) 謝謝點(diǎn)贊人乓!
- 本文相關(guān)海量書(shū)籍下載
- python官方文檔:https://docs.python.org/3/library/collections.html
- https://pymotw.com/3/collections/chainmap.html
- http://collections-extended.lenzm.net/
- https://pypi.python.org/pypi/collections-extended/
- 本文代碼地址