Counter

 
1
2
from collections import Counter
Counter([1, 1, 2, 3, 4])
Counter({1: 2, 2: 1, 3: 1, 4: 1})

collections.Counter class는 str, list 등 해시 가능한 객체가 포함하고 있는 원소들의 개수를 dictionary 형태로 세어주는 역할을 한다.

1
2
3
4
5
6
7
8
9
from collections import Counter

d1 = Counter([1, 1, 2, 3, 4])
d2 = Counter((1, 1, 2, 3, 4))
d3 = Counter({1, '1', 2, 3, 4})
d4 = Counter({1: 1, '1': 2, 2: 1, 3: 1, 4:1})
d5 = Counter("11234")
d = [d1, d2, d3, d4, d5]
d
[Counter({1: 2, 2: 1, 3: 1, 4: 1}),
 Counter({1: 2, 2: 1, 3: 1, 4: 1}),
 Counter({1: 1, 2: 1, 3: 1, 4: 1, '1': 1}),
 Counter({1: 1, '1': 2, 2: 1, 3: 1, 4: 1}),
 Counter({'1': 2, '2': 1, '3': 1, '4': 1})]


다음과 같이 사용할 수 있다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
c = Counter()                           # a new, empty counter
c = Counter('gallahad')                 # a new counter from an iterable
c = Counter({'red': 4, 'blue': 2})      # a new counter from a mapping
c = Counter(cats=4, dogs=8)             # a new counter from keyword args


c = Counter(['eggs', 'ham'])
c['bacon']                              # 0 (count of a missing element is zero)


c['sausage'] = 0                        # counter entry with a zero count
del c['sausage']                        # del actually removes the entry


c = Counter(a=4, b=2, c=0, d=-2)
sorted(c.elements())                    # ['a', 'a', 'a', 'a', 'b', 'b']


Counter('abracadabra').most_common(3)   # [('a', 5), ('b', 2), ('r', 2)]


c = Counter(a=4, b=2, c=0, d=-2)
d = Counter(a=1, b=2, c=3, d=4)
c.subtract(d)
c                                       # Counter({'a': 3, 'b': 0, 'c': -3, 'd': -6})


sum(c.values())                 # total of all counts
c.clear()                       # reset all counts
list(c)                         # list unique elements
set(c)                          # convert to a set
dict(c)                         # convert to a regular dictionary
c.items()                       # convert to a list of (elem, cnt) pairs
Counter(dict(list_of_pairs))    # convert from a list of (elem, cnt) pairs
c.most_common()[:-n-1:-1]       # n least common elements
+c                              # remove zero and negative counts


c = Counter(a=3, b=1)
d = Counter(a=1, b=2)
c + d                       # Counter({'a': 4, 'b': 3}) (add two counters together:  c[x] + d[x])
c - d                       # Counter({'a': 2}) (subtract (keeping only positive counts)
c & d                       # Counter({'a': 1, 'b': 1}) (intersection:  min(c[x], d[x]))
c | d                       # Counter({'a': 3, 'b': 2}) (union:  max(c[x], d[x]))


c = Counter(a=2, b=-4)
+c                          # Counter({'a': 2})
-c                          # Counter({'b': 4})

c = Counter(a=1, b=0, c=-1)
c += Counter()
c  # Counter({'a': 1}) (save positive counts)