Python 作為一個“內(nèi)置電池”的編程語言仿粹,標準庫里面擁有非常多好用的模塊千绪。比如今天想給大家 介紹的 collections
就是一個非常好的例子萎河。
基本介紹
我們都知道焦除,Python 擁有一些內(nèi)置的數(shù)據(jù)類型,比如 str, int, list, tuple, dict 等英古, collections 模塊在這些內(nèi)置數(shù)據(jù)類型的基礎上淀衣,提供了幾個額外的數(shù)據(jù)類型:
-
ChainMap
:將多個字典組成一個新的單元,Python3 新特性召调; -
Counter
:計數(shù)器膨桥,主要用來計數(shù)蛮浑; -
deque
:雙端隊列,可以快速的從另外一側追加和推出對象只嚣; -
namedtuple
:生成可以使用名字來訪問元素內(nèi)容的 tuple 子類沮稚; -
defaultdict
:帶有默認值的字典; -
OrderedDict
:有序字典册舞。
ChainMap
用 ChainMap
來管理字典序列蕴掏,并且通過順序搜索來找到 key
對應的值。
訪問值
ChainMap
和普通字典一樣调鲸,支持相同的 API 訪問現(xiàn)有的值盛杰。
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('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)))
# output
# Individual Values
# a = A
# b = B
# c = C
#
# Keys = ['c', 'b', 'a']
# Values = ['C', 'B', 'A']
#
# Items:
# c = C
# b = B
# a = A
#
# "d" in m: False
ChainMap
按照傳遞給它的順序進行搜索,所以鍵 c
對應的值來自字典 a
藐石。
重新排序
可以通過 maps
屬性將結果以列表形式返回即供。由于列表是可變的,所以可以對這個列表重新排序贯钩,或者添加新的值募狂。
import collections
a = {'a': 'A', 'c': 'C'}
b = {'b': 'B', 'c': 'D'}
m = collections.ChainMap(a, b)
print(m.maps) # [{'a': 'A', 'c': 'C'}, {'b': 'B', 'c': 'D'}]
print('c = {}\n'.format(m['c'])) # c = C
# reverse the list
m.maps = list(reversed(m.maps))
print(m.maps) # [{'b': 'B', 'c': 'D'}, {'a': 'A', 'c': 'C'}]
print('c = {}'.format(m['c'])) # c = D
更新值
ChainMap
不會給子映射創(chuàng)建一個單獨的空間,所以對子映射修改時角雷,結果也會反饋到 ChainMap
上祸穷。
import collections
a = {'a': 'A', 'c': 'C'}
b = {'b': 'B', 'c': 'D'}
m = collections.ChainMap(a, b)
print('Before: {}'.format(m['c'])) # Before: C
a['c'] = 'E'
print('After : {}'.format(m['c'])) # After : E
也可以通過 ChainMap
直接設置值,實際上只修改了第一個字典中的值勺三。
import collections
a = {'a': 'A', 'c': 'C'}
b = {'b': 'B', 'c': 'D'}
m = collections.ChainMap(a, b)
print('Before:', m) # Before: ChainMap({'a': 'A', 'c': 'C'}, {'b': 'B', 'c': 'D'})
m['c'] = 'E'
print('After :', m) # After : ChainMap({'a': 'A', 'c': 'E'}, {'b': 'B', 'c': 'D'})
print('a:', a) # a: {'a': 'A', 'c': 'E'}
ChainMap
提供了一個簡單的方法雷滚,用于在maps
列表的前面創(chuàng)建一個新實例,這樣做的好處是可以避免修改現(xiàn)有的底層數(shù)據(jù)結構吗坚。
import collections
a = {'a': 'A', 'c': 'C'}
b = {'b': 'B', 'c': 'D'}
m1 = collections.ChainMap(a, b)
m2 = m1.new_child()
print(m1) # ChainMap({'a': 'A', 'c': 'C'}, {'b': 'B', 'c': 'D'})
print(m2) # ChainMap({}, {'a': 'A', 'c': 'C'}, {'b': 'B', 'c': 'D'})
m2['c'] = 'E'
print(m1) # ChainMap({'a': 'A', 'c': 'C'}, {'b': 'B', 'c': 'D'})
print(m2) # ChainMap({'c': 'E'}, {'a': 'A', 'c': 'C'}, {'b': 'B', 'c': 'D'})
這種堆疊行為使得將ChainMap
實例用作模板或應用程序上下文變得非常方便祈远。具體來說,在一次迭代中很容易添加或更新值商源,然后丟棄下一次迭代的更改车份。
對于新上下文已知或預先構建的情況,也可以將映射傳遞給new_child()
牡彻。
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'])) # m1["c"] = C
print('m2["c"] = {}'.format(m2['c'])) # m2["c"] = E
這相當于:
m2 = collections.ChainMap(c, *m1.maps)
Counter
Counter
函數(shù)用來統(tǒng)計一個容器中相等值出現(xiàn)的次數(shù)扫沼。
初始化
Counter
支持三種初始化形式:
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))
# output
# Counter({'b': 3, 'a': 2, 'c': 1})
# Counter({'b': 3, 'a': 2, 'c': 1})
# Counter({'b': 3, 'a': 2, 'c': 1})
Counter
初始化時也可以不傳參數(shù),然后通過update()
方法更新庄吼。
import collections
c = collections.Counter()
print('Initial :', c) # Initial : Counter()
c.update('abcdaab')
print('Sequence:', c) # Sequence: Counter({'a': 3, 'b': 2, 'c': 1, 'd': 1})
c.update({'a': 1, 'd': 5})
print('Dict :', c) # Dict : Counter({'d': 6, 'a': 4, 'b': 2, 'c': 1})
計數(shù)值基于新數(shù)據(jù)而不是替換而增加缎除。在上例中,計數(shù)a
從3
到 4
总寻。
訪問計數(shù)
Counter
中的值器罐,可以使用字典 API 獲取它的值。
import collections
c = collections.Counter('abcdaab')
for letter in 'abcde':
print('{} : {}'.format(letter, c[letter]))
# output
# a : 3
# b : 2
# c : 1
# d : 1
# e : 0
對于 Counter
中沒有的鍵渐行,不會報 KeyError
轰坊。如本例中的 e
铸董,將其計數(shù)為0
。
elements()
方法返回一個迭代器衰倦,遍歷它可以獲得 Counter
中的值袒炉。
import collections
c = collections.Counter('extremely')
c['z'] = 0
print(c) # Counter({'e': 3, 'x': 1, 't': 1, 'r': 1, 'm': 1, 'l': 1, 'y': 1, 'z': 0})
print(list(c.elements())) # ['e', 'e', 'e', 'x', 't', 'r', 'm', 'l', 'y']
不保證元素的順序,并且不包括計數(shù)小于或等于零的值樊零。
使用most_common()
產(chǎn)生序列最常遇到的輸入值和它們各自的計數(shù)我磁。
import collections
c = collections.Counter()
with open('/usr/share/dict/words', 'rt') as f:
for line in f:
c.update(line.rstrip().lower())
print('Most common:')
for letter, count in c.most_common(3):
print('{}: {:>7}'.format(letter, count))
# output
# Most common:
# e: 235331
# i: 201032
# a: 199554
此示例計算在系統(tǒng)字典所有單詞中的字母生成頻率分布,然后打印三個最常見的字母驻襟。如果沒有參數(shù)的話夺艰,會按頻率順序生成所有項目的列表。
算術
Counter
實例支持算術和聚合結果沉衣。這個例子顯示了標準的操作符計算新的Counter
實例郁副,就地操作符 +=
,-=
豌习,&=
存谎,和|=
也支持。
import collections
c1 = collections.Counter(['a', 'b', 'c', 'a', 'b', 'b'])
c2 = collections.Counter('alphabet')
print('C1:', c1)
print('C2:', 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)
# output
# C1: Counter({'b': 3, 'a': 2, 'c': 1})
# C2: Counter({'a': 2, 'l': 1, 'p': 1, 'h': 1, 'b': 1, 'e': 1, 't': 1})
#
# Combined counts:
# Counter({'a': 4, 'b': 4, 'c': 1, 'l': 1, 'p': 1, 'h': 1, 'e': 1, 't': 1})
#
# Subtraction:
# Counter({'b': 2, 'c': 1})
#
# Intersection (taking positive minimums):
# Counter({'a': 2, 'b': 1})
#
# Union (taking maximums):
# Counter({'b': 3, 'a': 2, 'c': 1, 'l': 1, 'p': 1, 'h': 1, 'e': 1, 't': 1})
每次Counter
通過操作產(chǎn)生新的時肥隆,任何具有零或負計數(shù)的項目都將被丟棄既荚。計數(shù)a
在c1
和c2
中是相同的,因此相減之后變?yōu)榱恪?/p>
deque
雙端隊列栋艳,支持在隊列的任意一端添加和刪除元素恰聘,常用的堆棧和隊列可以看做是它的簡化形式。
import collections
d = collections.deque('abcdefg')
print('Deque:', d) # Deque: deque(['a', 'b', 'c', 'd', 'e', 'f', 'g'])
print('Length:', len(d)) # Length: 7
print('Left end:', d[0]) # Left end: a
print('Right end:', d[-1]) # Right end: g
d.remove('c')
print('remove(c):', d) # remove(c): deque(['a', 'b', 'd', 'e', 'f', 'g'])
deques
是一種序列容器吸占,它們支持一些類似于 list
的操作晴叨,例如求長度,從中刪除某個元素等矾屯。
填充
可以從任一端填充雙端隊列兼蕊,在 Python 實現(xiàn)中稱為“左”和“右”。
import collections
# Add to the right
d1 = collections.deque()
d1.extend('abcdefg')
print('extend :', d1) # extend : deque(['a', 'b', 'c', 'd', 'e', 'f', 'g'])
d1.append('h')
print('append :', d1) # append : deque(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'])
# Add to the left
d2 = collections.deque()
d2.extendleft(range(6))
print('extendleft:', d2) # extendleft: deque([5, 4, 3, 2, 1, 0])
d2.appendleft(6)
print('appendleft:', d2) # appendleft: deque([6, 5, 4, 3, 2, 1, 0])
extendleft()
函數(shù)迭代其輸入件蚕,相當于對每一項執(zhí)行 appendleft()
遍略。最終結果是以deque
相反的順序插入序列。
消費
類似地骤坐,deque
取決于所應用的算法,可以從兩端或任一端消耗元素下愈。
import collections
print('From the right:')
d = collections.deque('abcdefg')
while True:
try:
print(d.pop(), end='')
except IndexError:
break
print()
print('\nFrom the left:')
d = collections.deque(range(6))
while True:
try:
print(d.popleft(), end='')
except IndexError:
break
print()
# output
# From the right:
# gfedcba
# From the left:
# 012345
用pop()
從“右”端移除項目纽绍,用 popleft()
從“左”端獲取項目。
由于deques
是線程安全的势似,所以可以用不同線程同時從雙端取數(shù)據(jù)拌夏。
import collections
import threading
import time
candle = collections.deque(range(5))
def burn(direction, nextSource):
while True:
try:
next = nextSource()
except IndexError:
break
else:
print('{:>8}: {}'.format(direction, next))
time.sleep(0.1)
print('{:>8} done'.format(direction))
return
left = threading.Thread(target=burn, args=('Left', candle.popleft))
right = threading.Thread(target=burn, args=('Right', candle.pop))
left.start()
right.start()
left.join()
right.join()
# output
# Left: 0
# Right: 4
# Right: 3
# Left: 1
# Right: 2
# Left done
# Right done
刪除項目直到deque
為空僧著。
旋轉
另一個有用的方面是 deque
能夠在任一方向上旋轉,可以通過這個方法跳過一些項目障簿。
import collections
d = collections.deque(range(10))
print('Normal :', d) # Normal : deque([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
d = collections.deque(range(10))
d.rotate(2)
print('Right rotation:', d) # Right rotation: deque([8, 9, 0, 1, 2, 3, 4, 5, 6, 7])
d = collections.deque(range(10))
d.rotate(-2)
print('Left rotation :', d) # Left rotation : deque([2, 3, 4, 5, 6, 7, 8, 9, 0, 1])
deque
向右旋轉(使用正向旋轉)從右端獲取項目并將它們移動到左端盹愚。向左旋轉(帶負值)從左端獲取項目并將它們移動到右端。
約束隊列大小
一個deque
實例可以設置最大長度站故。當隊列達到指定長度時皆怕,將在添加新項目時丟棄現(xiàn)有項目。
import collections
import random
# Set the random seed so we see the same output each time
# the script is run.
random.seed(1)
d1 = collections.deque(maxlen=3)
d2 = collections.deque(maxlen=3)
for i in range(5):
n = random.randint(0, 100)
print('n =', n)
d1.append(n)
d2.appendleft(n)
print('D1:', d1)
print('D2:', d2)
# output
# n = 17
# D1: deque([17], maxlen=3)
# D2: deque([17], maxlen=3)
# n = 72
# D1: deque([17, 72], maxlen=3)
# D2: deque([72, 17], maxlen=3)
# n = 97
# D1: deque([17, 72, 97], maxlen=3)
# D2: deque([97, 72, 17], maxlen=3)
# n = 8
# D1: deque([72, 97, 8], maxlen=3)
# D2: deque([8, 97, 72], maxlen=3)
# n = 32
# D1: deque([97, 8, 32], maxlen=3)
# D2: deque([32, 8, 97], maxlen=3)
無論項目添加到哪一端西篓,都會保持雙端隊列長度愈腾。
namedtuple
標準tuple
使用數(shù)字索引來訪問其成員。
bob = ('Bob', 30, 'male')
print('Representation:', bob)
jane = ('Jane', 29, 'female')
print('\nField by index:', jane[0])
print('\nFields by index:')
for p in [bob, jane]:
print('{} is a {} year old {}'.format(*p))
# output
# Representation: ('Bob', 30, 'male')
#
# Field by index: Jane
#
# Fields by index:
# Bob is a 30 year old male
# Jane is a 29 year old female
但通過索引來訪問的方式可能會引起錯誤岂津,特別是當 tuple
有很多字段的時候虱黄。使用 namedtuple
的好處就是為每個成員分配了名稱和索引。
定義
namedtuple
和常用元組的效率是一樣的吮成,由 namedtuple()
工廠函數(shù)創(chuàng)建橱乱。參數(shù)是新類的名稱和包含元素名稱的字符串。
import collections
Person = collections.namedtuple('Person', 'name age')
bob = Person(name='Bob', age=30)
print('\nRepresentation:', bob)
jane = Person(name='Jane', age=29)
print('\nField by name:', jane.name)
print('\nFields by index:')
for p in [bob, jane]:
print('{} is {} years old'.format(*p))
# output
# Representation: Person(name='Bob', age=30)
#
# Field by name: Jane
#
# Fields by index:
# Bob is 30 years old
# Jane is 29 years old
如示例所示粱甫,namedtuple
可以使用點式表示法(obj.attr
)按名稱來訪問字段泳叠。
就像普通的tuple
,namedtuple
也是不可改變的魔种。
import collections
Person = collections.namedtuple('Person', 'name age')
pat = Person(name='Pat', age=12)
print('\nRepresentation:', pat)
pat.age = 21
# output
# Representation: Person(name='Pat', age=12)
# Traceback (most recent call last):
# File "collections_namedtuple_immutable.py", line 17, in
# <module>
# pat.age = 21
# AttributeError: can't set attribute
嘗試通過其命名屬性更改值會導致 AttributeError
析二。
無效的字段名稱
如果字段名稱重復或與 Python 關鍵字沖突,則字段名稱無效节预。
import collections
try:
collections.namedtuple('Person', 'name class age')
except ValueError as err:
print(err)
try:
collections.namedtuple('Person', 'name age age')
except ValueError as err:
print(err)
# output
# Type names and field names cannot be a keyword: 'class'
# Encountered duplicate field name: 'age'
在解析字段名稱時叶摄,無效值會導致 ValueError
異常。
將rename
選項設置為True
來重命名無效字段安拟。
import collections
with_class = collections.namedtuple(
'Person', 'name class age',
rename=True)
print(with_class._fields) # ('name', '_1', 'age')
two_ages = collections.namedtuple(
'Person', 'name age age',
rename=True)
print(two_ages._fields) # ('name', 'age', '_2')
重命名字段的新名稱取決于它們在元組中的索引蛤吓,因此,名稱字段class
將變?yōu)?code>_1糠赦,重復字段 age
將更改為_2
会傲。
特殊屬性
namedtuple
提供了幾個有用的屬性和方法來處理子類和實例。所有這些內(nèi)置屬性都有一個下劃線(_
)為前綴的名稱拙泽,在大多數(shù) Python 程序中淌山,按照慣例表示私有屬性。對于 namedtuple
顾瞻,前綴是為了防止名稱和用戶提供的屬性名稱沖突泼疑。
傳遞給namedtuple
定義新類的字段名稱保存在_fields
屬性中。
import collections
Person = collections.namedtuple('Person', 'name age')
bob = Person(name='Bob', age=30)
print('Representation:', bob) # Representation: Person(name='Bob', age=30)
print('Fields:', bob._fields) # Fields: ('name', 'age')
雖然參數(shù)是單個空格分隔的字符串荷荤,但存儲的值是各個名稱的序列退渗。
namedtuple
實例可以使用 _asdict()
轉換為OrderedDict
實例移稳。
import collections
Person = collections.namedtuple('Person', 'name age')
bob = Person(name='Bob', age=30)
print('Representation:', bob)
print('As Dictionary:', bob._asdict())
# output
# Representation: Person(name='Bob', age=30)
# As Dictionary: OrderedDict([('name', 'Bob'), ('age', 30)])
OrderedDict
的鍵與 namedtuple
字段的順序相同。
_replace()
方法構建一個新實例会油,替換進程中某些字段的值个粱。
import collections
Person = collections.namedtuple('Person', 'name age')
bob = Person(name='Bob', age=30)
print('\nBefore:', bob) # Before: Person(name='Bob', age=30)
bob2 = bob._replace(name='Robert')
print('After:', bob2) # After: Person(name='Robert', age=30)
print('Same?:', bob is bob2) # Same?: False
雖然名稱暗示它在修改現(xiàn)有對象,但由于namedtuple
實例是不可變的翻翩,實際上都许,該方法返回了一個新對象。
defaultdict
標準字典包括 setdefault()
方法体斩,用于檢索值并在值不存在時建立默認值梭稚。相反,defaultdict
讓初始化容器時絮吵,調(diào)用者可以預先指定默認值弧烤。
import collections
def default_factory():
return 'default value'
d = collections.defaultdict(default_factory, foo='bar')
print('d:', d)
print('foo =>', d['foo'])
print('bar =>', d['bar'])
# output
# d: defaultdict(<function default_factory at 0x101341950>, {'foo': 'bar'})
# foo => bar
# bar => default value
所有鍵具有相同的默認值。如果默認值是聚合或累加類型的話(比如:list
蹬敲、set
暇昂、int
),尤其有用伴嗡。
In[88]: from collections import defaultdict
In[89]: d = defaultdict(int)
In[90]: d['a']
Out[90]: 0
In[91]: d = defaultdict(dict)
In[92]: d['a']
Out[92]: {}
如果初始化時沒有加入默認工廠急波,則會拋出 KeyError
錯誤:
In[93]: d = defaultdict()
In[94]: d['a']
Traceback (most recent call last):
d['a']
KeyError: 'a'
OrderedDict
OrderedDict
是一個字典子類,它會記住添加內(nèi)容的順序瘪校。
import collections
print('Regular dictionary:')
d = {}
d['a'] = 'A'
d['b'] = 'B'
d['c'] = 'C'
for k, v in d.items():
print(k, v)
print('\nOrderedDict:')
d = collections.OrderedDict()
d['a'] = 'A'
d['b'] = 'B'
d['c'] = 'C'
for k, v in d.items():
print(k, v)
# output
# Regular dictionary:
# c C
# b B
# a A
#
# OrderedDict:
# a A
# b B
# c C
相等
dict
在測試相等性時澄暮,只是查看其內(nèi)容。但 OrderedDict
還考慮了添加項目的順序阱扬。
import collections
print('dict :', end=' ')
d1 = {}
d1['a'] = 'A'
d1['b'] = 'B'
d1['c'] = 'C'
d2 = {}
d2['c'] = 'C'
d2['b'] = 'B'
d2['a'] = 'A'
print(d1 == d2)
print('OrderedDict:', end=' ')
d1 = collections.OrderedDict()
d1['a'] = 'A'
d1['b'] = 'B'
d1['c'] = 'C'
d2 = collections.OrderedDict()
d2['c'] = 'C'
d2['b'] = 'B'
d2['a'] = 'A'
print(d1 == d2)
# output
# dict : True
# OrderedDict: False
在這種情況下泣懊,由于兩個有序詞典是以不同順序的值創(chuàng)建的,因此它們被認為是不同的麻惶。
重新排序
可以通過使用 move_to_end()
將鍵移動到序列的開頭或結尾馍刮。
import collections
d = collections.OrderedDict(
[('a', 'A'), ('b', 'B'), ('c', 'C')]
)
print('Before:')
for k, v in d.items():
print(k, v)
d.move_to_end('b')
print('\nmove_to_end():')
for k, v in d.items():
print(k, v)
d.move_to_end('b', last=False)
print('\nmove_to_end(last=False):')
for k, v in d.items():
print(k, v)
# output
# Before:
# a A
# b B
# c C
#
# move_to_end():
# a A
# c C
# b B
#
# move_to_end(last=False):
# b B
# a A
# c C
last
參數(shù)指示move_to_end()
是否將鍵移動到序列中的最后一項(True
)或第一項(False
)。
相關文檔: