collections--容器數(shù)據(jù)類型
Counter
Counter作為一個(gè)容器,可以跟蹤相同的值增加了多少次。
Counter支持3種形式的初始化。調(diào)用Counter的構(gòu)造函數(shù)時(shí)可以提供一個(gè)元素序列或者一個(gè)包含鍵和計(jì)數(shù)的字典,還可以使用關(guān)鍵字參數(shù)將字符串名映射到計(jì)數(shù)。
#! /usr/bin/env python
#coding=utf-8
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)
如果不提供任何參數(shù),可以構(gòu)造一個(gè)空的Counter,然后通過(guò)update()方法填充
#! /usr/bin/env python
#coding=utf-8
import collections
c = collections.Counter()
print 'Initial:', c
c.update('abcdaab')
print 'Sequence:', c
c.update({'a': 1, 'd': 5})
print 'Dict:', c
計(jì)值將根據(jù)新數(shù)據(jù)增加, 替換數(shù)據(jù)不會(huì)改變計(jì)數(shù)
訪問(wèn)計(jì)數(shù)
#! /usr/bin/env python
#coding=utf-8
import collections
c = collections.Counter('abcdaab')
for letter in 'abcde':
print '%s : %d' %(letter, c[letter])
對(duì)于未知的元素,Counter不會(huì)產(chǎn)生KeyError。如果在輸入中沒(méi)有找到某個(gè)值,則其計(jì)數(shù)為0
elements()方法返回一個(gè)迭代器,將生成Counter知道的所有元素。
#! /usr/bin/env python
#coding=utf-8
import collections
c = collections.Counter('extremely')
c['z'] = 0
print c
print list(c.elements())
不能保證元素的順序不變,另外計(jì)數(shù)小于或等于0的元素不包含在內(nèi)。
使用most_common()可以生成一個(gè)序列,其中包含n個(gè)最常遇到的輸入值及其對(duì)應(yīng)計(jì)數(shù)。
#! /usr/bin/env python
#coding=utf-8
import collections
c = collections.Counter()
filepath = r'your real path'
with open(filepath, 'rt') as f:
for line in f:
c.update(line.rstrip().lower())
print 'Most common'
for letter, count in c.most_common(10):
print '%s: %7d' % (letter, count)
Counter實(shí)例支持算術(shù)和集合操作來(lái)完成結(jié)果的聚集
#! /usr/bin/env python
#coding=utf-8
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 '\nSunstraction'
print c1 - c2
print '\nIntersection (taking positive minumums)'
print c1 & c2
print '\nUnion (taking maximums)'
print c1 | c2
每次通過(guò)一個(gè)操作生成一個(gè)新的Counter時(shí),計(jì)數(shù)為0或負(fù)數(shù)的元素都會(huì)被刪除。
defaultdict
標(biāo)準(zhǔn)字典包括一個(gè)方法setdefault()來(lái)獲取一個(gè)值,如果這個(gè)值不存在則建立一個(gè)默認(rèn)值。與之相反,defaultdict初始化容器時(shí)會(huì)讓調(diào)用者提前指定默認(rèn)值。
#! /usr/bin/env python
#coding=utf-8
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']