参考:https://docs.python.org/2/library/collections.html#collections.Counter
collections包中有几种特殊容器,Counter是其中一种,存放的是对象出现次数,value值可以是0,正数和负数。
目录
1. Counter的创建
from collections import Counter
c = Counter(cats=4,dogs=5)
dic = Counter({'cats':3, 'dogs':4})
d = Counter('aabrdsd')
e = Counter(['hh', 'ee', 'hh'])
h = Counter(c)
print("key-value pair 创建为:\n",c,type(c))
print("由字典创建为:\n", dic)
print("字符串创建:\n", d)
print("由列表创建为:\n", e)
print("由Counter对象创建为:\n",h)
----
输出
key-value pair 创建为:
Counter({'dogs': 5, 'cats': 4}) <class 'collections.Counter'>
由字典创建为:
Counter({'dogs': 4, 'cats': 3})
字符串创建:
Counter({'a': 2, 'd': 2, 'b': 1, 'r': 1, 's': 1})
由列表创建为:
Counter({'hh': 2, 'ee': 1})
由Counter对象创建为:
Counter({'dogs': 5, 'cats': 4})
注意:
1. 若Counter中没有对象,则其值为0.
2. Counter中删除某个对象的方法是 del,将某个key的value设为0,并不能删除该元素。
2. Counter对象特有的3个方法(与dic相比)
(1)counter_obj.elements() : 返回一个迭代对象,迭代的内容是 每个key重复value词,如果value<=0,则没有该元素。
c = Counter(a=4, b=2, c=0, d=-4)
d = c.elements()
print(d, type(d))
print(list(d))
------
输出:
<itertools.chain object at 0x0000026362E986D8> <class 'itertools.chain'>
['a', 'a', 'a', 'a', 'b', 'b']
(2)counter_obj.most_common([n]) : 返回出现次数最多的n个key,返回结果自动按照次数排序,如果没有设置n,则返回所有的元素,包括次数小于等于0的。
c = Counter(a=4, b=2, c=0, d=-4)
c.most_common(3)
-----
输出:
[('a', 4), ('b', 2), ('c', 0)]
(3) counter_obj.subtract([iterable or mapping]) : 两个Counter对应键相减,没有的key视为0.
c = Counter(a=4, b=2, c=0, d=-4,e=1)
d = Counter(a=1, b=2, c=3, d=4)
c.subtract(d)
print(c)
-----
输出:
Counter({'a': 3, 'e': 1, 'b': 0, 'c': -3, 'd': -8})
3. 与dic相同方法不同含义
counter_obj没有方法fromkeys()
# 字典中 fromkeys() 方法
seq = ('Google', 'Runoob', 'Taobao')
dic = dict.fromkeys(seq)
print(dic)
dic2 = dict.fromkeys(seq,1)
print(dic2)
-----
输出:
{'Google': None, 'Runoob': None, 'Taobao': None}
{'Google': 1, 'Runoob': 1, 'Taobao': 1}
update() 字典中update方法会直接覆盖原有的值,在Counter中相同值会累加.
c = Counter(['Google', 'Runoob', 'Taobao'])
d = Counter(['Google', 'Runoob','JD'])
c.update(d)
print(c)
------
输出:
Counter({'Google': 2, 'Runoob': 2, 'Taobao': 1, 'JD': 1})
4. Counter的数学运算
c = Counter(a=3, b=1,c = 2)
d = Counter(a=1, b=2)
print(c+d) # 减法适用
print(c|d) # 取出现次数最大的
print(c&d) # 取出现次数的交集
---
输出:
Counter({'a': 4, 'b': 3, 'c': 2})
Counter({'a': 3, 'b': 2, 'c': 2})
Counter({'a': 1, 'b': 1})
2. deque 双端队列
2.1. deque作用
双端队列是一个生成器,可以在任意一端插入或删除,时间复杂度为O(1)。适用于固定长度,当队列满时,再添加新的元素,将会从另一端删除旧元素。
from collections import deque
deck = deque(iterable, length=None)
2.2 deque增删改查操作
deck.append(x) # Add x to the right side of the deque
deck.appendleft(x) # add x to the left side of the deque
deck.clear() # remove all elements
deck.count(x) # count the number of deque elements equal to x
deck.extend(iterable) # extend the right side of the deque by appending elements from the
# iterable argument
deck.extendleft(iterable)
deck.pop() # remove and return an element from the left side of the deque. if no elements
# are present, raises an IndexError
deck.popleft()
deck.remove(vale) # remove the first occurrence of value. if not found, raises a
# ValueError.
deck.reverse() # Reverse the elements of the deque in-place and then return None
deck.rotate(n=1) # Rotate the deque n steps to the right, if n is negative, rotate to the
# left.
deck.maxlen # maximum size of a deque or None if unbounded.
2.3 deque其他操作
- len(d)
- reversed(d)
- copy.copy(d)
- copy.deepcopy(d)
from collections import deque
d = deque('ghi')
d.append('j')
print(d)
print(len(d))
print(d.pop()) # 返回元素
h = d.remove('g') # 返回None
print(d, h)
d.extend('hello')
print("d.extend: ", d)
print(list(reversed(d)))
lst = list('ghi')
lst.reverse()
print("逆转list:", lst)
----Output-------
deque(['g', 'h', 'i', 'j'])
4
j
deque(['h', 'i']) None
d.extend: deque(['h', 'i', 'h', 'e', 'l', 'l', 'o'])
['o', 'l', 'l', 'e', 'h', 'i', 'h']
逆转list: ['i', 'h', 'g']