Pythonでは、よく使われる組み込みコンテナの dict
、list
、set
、tuple
に代わる特殊なコンテナがあり、collections
モジュールにまとまっている。今回はその中にある辞書型のサブクラスであるCounter
を使ってリストなどの要素の出現回数を数え、簡単に集計をしてみる。
まずは、Counter
を使わなかった場合の実装になる。
printと空行を除けば、7行での実装になる。
programming_languages = ['Python', 'Ruby', 'Go','Python','JavaScript', 'Go','Python','TypeScript','Python','TypeScript'] count = {} for pl in programming_languages: if pl in count: count[pl] += 1 else: count[pl] = 1 print(count)
Counter
を使うと下記のようになる。
printと空行を除けば、3行での実装になり、シンプルになった。
from collections import Counter programming_languages = ['Python', 'Ruby', 'Go','Python','JavaScript', 'Go','Python','TypeScript','Python','TypeScript'] count = Counter(programming_languages) for k, v in count.items(): print(k + ':' + str(v))
返ってくるのが辞書型なので、items()
などのメソッドを使うこともできる!