1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[Python]カウントだけじゃない collections.Counter

Last updated at Posted at 2020-03-19

概要

iterable の要素数を取得する collections.Counter の性質についてまとめた。
カウント以外にも dict にはない便利な性質が備わっているので、積極的に使っていきたい。

演算

加減算と集合の演算ができる。値がゼロ以下になったキーは自動的に削除される。

from collections import Counter

A = Counter('ab') # Counter({'a': 1, 'b': 1})
B = Counter('bc') # Counter({'c': 1, 'b': 1})
A + B # Counter({'b': 2, 'a': 1, 'c': 1})
A - B # Counter({'a': 1})
A & B # Counter({'b': 1})
A | B # Counter({'a': 1, 'b': 1, 'c': 1})

メソッド

演算子とは違い、ゼロ以下の値のキーも保持される。elements は値が正のキーのみを返す。

from collections import Counter

A = Counter('ab')
B = Counter('bc')
C = Counter('ac')
C.update(A) # Counter({'a': 2, 'c': 1, 'b': 1})
A.subtract(B) # Counter({'a': 1, 'b': 0, 'c': -1})
A.most_common() # [('a', 1), ('b', 0), ('c', -1)]
sorted(C.elements()) # ['a', 'a', 'b', 'c']
sorted(A.elements()) # ['a']

参照

要素を直接変更すると、メソッドと同じくゼロ以下の値が許容される。
存在しない要素を参照すると例外にならず 0 が返る。

from collections import Counter

A = Counter('ab')
A['a'] += 2 # Counter({'a': 3, 'b': 1})
a['b'] -= 2 # Counter({'a': 3, 'b': -1})
A['c'] # 0

なお、単項演算子は空の Counter() に対する演算のショートカットになっている。
各要素ごとの演算後に、正または負の値だけを抽出できる。

A # Counter({'a': 3, 'b': -1})
+A # Counter({'a': 3})
-A # Counter({'b': 1})
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?