from collections import (Counter, deque, namedtuple, defaultdict, OrderedDict)
Counter
'''Dict subclass for counting hashable items. Sometimes called a bag
or multiset. Elements are stored as dictionary keys and their counts
are stored as dictionary values.
>>> c = Counter('abcdeabcdabcaba') # count elements from a string
>>> c.most_common(3) # three most common elements
[('a', 5), ('b', 4), ('c', 3)]
>>> sorted(c) # list all unique elements
['a', 'b', 'c', 'd', 'e']
>>> ''.join(sorted(c.elements())) # list elements with repetitions
'aaaaabbbbcccdde'
>>> sum(c.values()) # total of all counts
15
>>> c['a'] # count of letter 'a'
5
>>> for elem in 'shazam': # update counts from an iterable
... c[elem] += 1 # by adding 1 to each element's count
>>> c['a'] # now there are seven 'a'
7
>>> del c['b'] # remove all 'b'
>>> c['b'] # now there are zero 'b'
0
>>> d = Counter('simsalabim') # make another counter
>>> c.update(d) # add in the second counter
>>> c['a'] # now there are nine 'a'
9
>>> c.clear() # empty the counter
>>> c
Counter()
Note: If a count is set to zero or reduced to zero, it will remain
in the counter until the entry is deleted or the counter is cleared:
>>> c = Counter('aaabbc')
>>> c['b'] -= 2 # reduce the count of 'b' by two
>>> c.most_common() # 'b' is still in, but its count is zero
[('a', 3), ('c', 1), ('b', 0)]
cnt = Counter()
wordList = ["a", "b", "c", "c", "a", "a"]
for word in wordList:
cnt[word] += 1
print(cnt)
print(list(cnt.elements()))
print(cnt.most_common(1))
deque
# 栈和队列的广义实现 支持线程安全 有效的内存 近似O(1)
# 相关方法
d = deque('abc')
for i in d:
print(i.upper())
# 右侧添加元素
d.append('R')
# 左侧添加元素
d.appendleft('L')
print(d)
# 返回和移除右侧元素
print(d.pop())
# 返回和移除左侧元素
print(d.popleft())
# 以list的形式展示
print(list(d))
# 下标 [i]
# 一次添加多个元素
d.extend('123')
print(d)
# 往右侧翻转
d.rotate(1)
print(d)
# 往左翻转
d.rotate(-1)
print(d)
## 维护一个序列
import itertools
def moving_average(iterable, n=3):
it = iter(iterable)
d = deque(itertools.islice(it, n - 1))
# 第一次只有两个元素,再右移的过程中,需要先删除最左端的元素,因此现在最左端加入0
d.appendleft(0)
s = sum(d)
for ele in it:
# 删除最左端的元素,再加上新元素
s += ele - d.popleft()
# 右端添加新元素
d.append(ele)
yield s / float(n)
array = [40, 30, 50, 46, 39, 44]
for ele in moving_average(array, n=3):
print(ele)
namedtuple
"""Returns a new subclass of tuple with named fields."""
P = namedtuple('P', ['x', 'y'])
p = P(1, 2)
print(p.x)
print(p.y)
defaultdict
dd = defaultdict(lambda: 'N/A')
print(dd["key"])
OrderedDict
#实现了对字典对象中元素的排序
d = dict([('a', 1), ('b', 2), ('c', 3)])
print(d)
od = OrderedDict([('a', 1), ('c', 2), ('b', 3)])
print(od)