2010年4月22日木曜日

Python2.7のCounterを使ってみた



python2.7(2010年4月21日現在まだベータですが)で追加されるクラスの一つに Counter があります。


7.3. collections ? Container datatypes — Python v3.2rc2 documentation


その名の通り何かしらのデータをカウントするときに使えるクラスです。


例えば今までは



d = {}

d['foo'] = d.get('foo',0) + 1
d['bar'] = d.get('bar',0) + 1
d['foo'] = d.get('foo',0) + 1

for key,value in d.items():
print key,value


なんて書いていたのが



from collections import Counter

c = Counter()

c['foo'] += 1
c['bar'] += 1
c['foo'] += 1

for key,value in c.items():
print key,value


で済むようになります。


また、most_common()を使えば手軽にソートできます(上記リンクから参照)。



>>> # Find the ten most common words in Hamlet
>>> import re
>>> words = re.findall('\w+', open('hamlet.txt').read().lower())
>>> Counter(words).most_common(10)
[('the', 1143), ('and', 966), ('to', 762), ('of', 669), ('i', 631),
('you', 554), ('a', 546), ('my', 514), ('hamlet', 471), ('in', 451)]


今までのように辞書使ってると、一旦リストに変換して……とか面倒なステップを踏んでたのでこれはありがたいですね。


ちなみに、github に試しに作ったソースを載せました。


gist: 373850 - python2.7で追加されたCounterを試しに使ってみた。従来の辞書との使い方の比較。- GitHub





0 件のコメント: