
python勉強(itertools)
pythonの勉強した記録を残していきます。
itertoolsについてです。
Pythonでは、連続するデータをイテレーターを使って表現します。
イテレーターは__next__()メソッドを呼び出すと値を返してくれます。
itertoolsモジュールのgroupby()関数
イテラブルオブジェクトをグループ化したイテレーターを返す。
実際のコード
import itertools
sorted_text = ''.join(sorted('aaaaannhngdteeeurff')) # 文字列単位でソートする。
for value, group in itertools.groupby(sorted_text):
print(f'{value}: {list(group)}')
実行結果

イテラブルの組み合わせを行う関数。
product()→イテラブルオブジェクトのデカルト積を返す。
デカルト積とは各集合から一つずつ元をとりだして組にしたもの(元の族)を元として持つ新たな集合である。
コード
import itertools
n_list = list(itertools.product('ABC', [1, 2, 3]))
print(n_list)
実行結果

引数を指定
repeat→値を組み合わせる回数を指定する。
コード
import itertools
n_lsit_v1 = [i[0] + i[1] for i in itertools.product('ABC', repeat=2)] # 2パターンで組み合わせる
print(n_lsit_v1)
実行結果

permutations()関数は1つのイテラブルオブジェクトを指定し、順列を返す。
コード
import itertools
n_list_v2 = list(itertools.permutations('ABC'))
print(n_list_v2)
実行結果

itertoolsは各関数を用途に合わせて使うことで、様々なイテレーターを作ることが出来る。itertoolsは高速でメモリ効率がいいので、大量のデータを扱う場合に向いている。
以上になります。