初心者のためのpython入門

自分がつまづいたところやつまづきやすいところを中心に書いていきます。また、役に立つライブラリの紹介などをしていきます。

collections[2]

前書き

前回に続き、collectionsライブラリについて紹介します。

Counter

Counterは、リストやタプルなどのハッシュ可能なオブジェクトから値の出現回数を数え上げることができる辞書のサブクラスです。

from collections import Counter
l = [1 if i % 2 else 0 for i in range(10)] # リスト内包表記
c = Counter(l)
print(c)
print(c[0])
Counter({0: 5, 1: 5}) # print(c)
5 # print(c[0])

便利なメソッドとして以下のものがあります。

  • c.elements(): それぞれの要素をカウントの分だけ繰り返すイテレータを返す
  • c.most_common(n): 最も多いn要素を降順で返す. n=Noneなら全ての要素を返す
  • c.subtract(d): cの要素のカウント数からdの要素のカウント数を引く
c = Counter(a=5, b=4, c=3)
print(c.most_common())

print(c.elements())
print(sorted(c.elements()))

d = Counter(a=1, b=2, c=3, d=4)
c.subtract(d)
print(c)
[('a', 5), ('b', 4), ('c', 3)] # print(c.most_common())
<itertools.chain object at 0x104741438> # print(c.elements())
['a', 'a', 'a', 'a', 'a', 'b', 'b', 'b', 'b', 'c', 'c', 'c'] # print(sorted(c.elements()))
Counter({'a': 4, 'b': 2, 'c': 0, 'd': -4}) # print(c)

OrderedDict

OrderedDictは、要素が追加された順序を保持することができる辞書のサブクラスです。

from collections import OrderedDict
od = OrderedDict({'one': 1, 'two': 2, 'three': 3})
print(od)

od.move_to_end('two') #指定した要素を最後に移動
print(od)

od.move_to_end('two', last=False) # last=Falseなら最初に移動
print(od)
OrderedDict([('one', 1), ('two', 2), ('three', 3)])
OrderedDict([('one', 1), ('three', 3), ('two', 2)])
OrderedDict([('two', 2), ('one', 1), ('three', 3)])

defaultdict

defaultdictは、全てのキーに対してデフォルトの値を持っている辞書のサブクラスです。

from collections import defaultdict
dd = defaultdict(int)
print(d[0])

d = dict()
print(d[0])
0 # print(dd[0])
KeyError: 0 # print(d[0])

後書き

お疲れ様でした。今回の3つは、前回の3つよりも使用する機会が多いと思います。

Fluent Python ―Pythonicな思考とコーディング手法

Fluent Python ―Pythonicな思考とコーディング手法