0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Python初心者】itertoolsモジュールの使い方まとめ(chain / groupby / islice / 組み合わせ系)

Posted at

itertools モジュールの代表的な機能を整理しました。
大量のデータを効率よく処理したり、組み合わせや連結を簡単に行いたいときにとても役立つツールです。

itertools とは?

itertools は、繰り返し処理を効率よく行うための標準ライブラリです。
全体をメモリに読み込まずに「イテレータ(遅延処理)」で扱うのが特徴で、大量データでも軽く処理できます。

chain:複数のイテラブルを連結

chain() を使うと、複数のリストなどを1つにつなげたように扱えます。

from itertools import chain

a = [1, 2]
b = [3, 4]

for x in chain(a, b):
    print(x)

実行結果:

1
2
3
4
  • a + b のようにリスト同士を足すのと似ていますが、遅延評価でメモリ効率が良いのが特徴です
  • リスト以外のイテラブル(例えば range や文字列)にも使えます

groupby:連続した同じ値をまとめる

from itertools import groupby

data = ['A', 'A', 'B', 'B', 'B', 'A', 'A']

for key, group in groupby(data):
    print(key, list(group))

実行結果:

A ['A', 'A']
B ['B', 'B', 'B']
A ['A', 'A']

🔸 注意点

  • ソートされていないと「完全なグループ化」にはならない
  • groupby()連続する同一要素を1グループとして扱います
data = sorted(data)  # グループ化したい場合は事前にソート

islice:一部だけ取り出す(スライス)

islice() はリストのスライスに似ていますが、イテレータにも使えるのが強みです。

from itertools import islice

nums = range(10)

for x in islice(nums, 3, 7):
    print(x)

実行結果:

3
4
5
6
  • islice(iterable, start, stop) のように使います
  • 通常のスライス(a[start:stop])と違って、イテレータを途中から一部だけ処理できるのが便利です

組み合わせ系のツールまとめ

itertools には、組み合わせ・順列・直積などを求める便利な関数も揃っています。

product:直積(全ての組み合わせ)

from itertools import product

colors = ['red', 'blue']
sizes = ['S', 'M']

for item in product(colors, sizes):
    print(item)

実行結果:

('red', 'S')
('red', 'M')
('blue', 'S')
('blue', 'M')
  • product(A, B) は「A×B」の全ての組み合わせを出してくれます

permutations:順列(並び順あり)

from itertools import permutations

items = ['A', 'B', 'C']

for p in permutations(items, 2):
    print(p)

実行結果:

('A', 'B')
('A', 'C')
('B', 'A')
('B', 'C')
('C', 'A')
('C', 'B')
  • 順番が違うものは別の組として扱われます

combinations:組み合わせ(順不同)

from itertools import combinations

items = ['A', 'B', 'C']

for c in combinations(items, 2):
    print(c)

実行結果:

('A', 'B')
('A', 'C')
('B', 'C')
  • 順番は関係なく、同じペアは1回だけ出てきます

おわりに

今回は itertools モジュールの中でも、特によく使う chain()groupby()islice() と、組み合わせ系の関数についてまとめました。

通常の for 文や list 操作では難しい処理も、itertools を使えば短く書けることが分かってきました。特に組み合わせの生成はテストデータやUIのバリエーション生成などに応用できそうです。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?