![見出し画像](https://assets.st-note.com/production/uploads/images/93738373/rectangle_large_type_2_1006554a625af5c27f4808e8ec30ad6c.png?width=1200)
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)}')
実行結果
![](https://assets.st-note.com/img/1671543552107-Mq0k9GYx7T.png)
イテラブルの組み合わせを行う関数。
product()→イテラブルオブジェクトのデカルト積を返す。
デカルト積とは各集合から一つずつ元をとりだして組にしたもの(元の族)を元として持つ新たな集合である。
コード
import itertools
n_list = list(itertools.product('ABC', [1, 2, 3]))
print(n_list)
実行結果
![](https://assets.st-note.com/img/1671543938599-ZqMneUoATE.png?width=1200)
引数を指定
repeat→値を組み合わせる回数を指定する。
コード
import itertools
n_lsit_v1 = [i[0] + i[1] for i in itertools.product('ABC', repeat=2)] # 2パターンで組み合わせる
print(n_lsit_v1)
実行結果
![](https://assets.st-note.com/img/1671544129090-LgcihCWetp.png)
permutations()関数は1つのイテラブルオブジェクトを指定し、順列を返す。
コード
import itertools
n_list_v2 = list(itertools.permutations('ABC'))
print(n_list_v2)
実行結果
![](https://assets.st-note.com/img/1671544351664-LQxWPTC6bZ.png?width=1200)
itertoolsは各関数を用途に合わせて使うことで、様々なイテレーターを作ることが出来る。itertoolsは高速でメモリ効率がいいので、大量のデータを扱う場合に向いている。
以上になります。