Python3 collectionsモジュールの色々

collectionsモジュールの用途は広いため、一例を紹介。

[amazonjs asin="B009Z30HPG" locale="JP" title="Dive Into Python 3 日本語版"]

Counterメソッド

Counterメソッドは、引数のリストの要素の個数をカウントし、カウントが多い順に要素とカウントのペアを返す。
[shell]
In [1]: from collections import Counter

In [2]: a = [1, 2, 3, 4, 1, 2, 5, 4, 1, 2, 3, 3, 3, 5]

In [3]: Counter(a).most_common()
Out[3]: [(3, 4), (1, 3), (2, 3), (4, 2), (5, 2)]
[/shell]

逆に、Counterメソッドから要素と個数を指定してリストを作成することもできる。

[shell]
In [1]: from collections import Counter

In [2]: a = Counter(a=4, b=3, c=0, d=-1, e=2)

In [3]: list(a.elements())
Out[3]: ['a’, 'a’, 'a’, 'a’, 'e’, 'e’, 'b’, 'b’, 'b’]
[/shell]

 

OrderedDictメソッド

通常、pythonの辞書式変数は要素を追加しても順序が保たれずにソートされてしまう。

[shell]
In [1]: dic = dict(a=1, c=2)

In [2]: dic['b’] = 3

In [3]: dic
Out[3]: {'a’: 1, 'b’: 3, 'c’: 2}
[/shell]

そこでOrderedDictメソッドを使うことで、順序が保たれたまま辞書式変数と同様の実装ができる。

[shell]
In [1]: from collections import OrderedDict

In [2]: dic = OrderedDict((('a’, 1), ('c’, 2)))

In [3]: dic['b’] = 3

In [4]: dic
Out[4]: OrderedDict([('a’, 1), ('c’, 2), ('b’, 3)])
[/shell]

 

namedtupleメソッド

namedtupleはひとつの変数に複数の属性を実装したいときに便利。
クラス内に変数を作成したときのように扱うことができる。

[shell]
In [1]: from collections import namedtuple

In [2]: Point = namedtuple('Point’, ['x’, 'y’])

In [3]: Point.x = 10

In [4]: Point.y = 20

In [5]: Point.x, Point.y
Out[5]: (10, 20)
[/shell]

 

defaultdictメソッド

defaultdictメソッドは配列の同じ値を持つ要素をグループにして出力する。

[shell]
In [1]: from collections import defaultdict

In [2]: a = [('red’, 1), ('blue’, 2), ('red’, 3), ('green’, 4), ('green’,5)]

In [3]: d = defaultdict(list)

In [4]: for k,v in a:
…: d[k].append(v)
…:

In [5]: list(d.items())
Out[5]: [('blue’, [2]), ('red’, [1, 3]), ('green’, [4, 5])]
[/shell]