itertools
繰り返し処理を上手くさばきたい。forを使わずにスッキリ書きたい
メソッドチェインで書けると気持ちいいだろうけど、それは無理なはず
10.1. itertools — Functions creating iterators for efficient looping — Python 3.6.4 documentation
Functions creating iterators for efficient looping
大きく3つに別れるよう。
Infinite iterators 無限loopな 基本iterator作成。 これを土台にして、combine, terminateさせる。
count(), cycle(), repeat()
Iterators terminating on the shortest input sequence
普通の意味でのloop処理してくれる。処理の実態が関数名を表す
the shortest input sequenceのイメージがつかめない #question
ある条件で最小のsequenceで終端するという意味だろうけど。dropwhile, accumulate...終端?????
個別の関数は、
islice(seq, [start], stop) : 要素数でterminate (index指定)
takewhile(pred, seq) 要素の条件(predicate)でterminate
dropwhileと逆もある
filterfalse(pred, seq)
よく使う filterの逆。filterも python3で generatorを返すようになった.
compress(seq, filter_seq)
同じに長さ?のseq。後ろの方は yes, noでselectするためのリスト
accumulate(Iterable, func) func未指定で operator.add
chain(), chain.from_iterable(). iteratorする対象の延伸
groupby() こんな sub-iteratorsを作ってくれる。これ使いみちおおそうだが、、集計書ける?
sortしなければ、length encoding とかが簡単にできる。
[[z for z in x] for _, x in itertools.groupby(range(12), lambda x: math.floor(x/5))]
0-11までの数字を、0-4, 5-9, 10-11 と5つずつ切る。
starmap() mapと同じ。違いは、、、
tee(Iterable, n=2) iteratorの複製。 使用コストを考慮する?
Combinatonic iterators itertools 組み合わせ| python
product(), permutations(), combinations(), combinations_with_replacement()
下は、itertools の使い方、すごい. 簡潔で汎用的に書けるのは、データ処理で重要。
Lazy FizzBuzz (Python ver.)
f-string: The new f-strings in Python 3.6 | Seasoned & Agile
asterisk: What does asterisk * mean in Python? - Stack Overflow
yield from iterableをうまく使ってる。..
repeat, cycle, count, islice
repeat, cycle, countなどはいつまでも続くので、isliceで終わりをつけるために、切り取る。
streaming処理みたいなものを想定かもなので、現実に使う場面はどうかな、汎用的なモデルとかにはいいかも
ジェネレーターを作って、ジェネレーターで揃えて、最終的に iterateする形。
accumulateは、docにカオス生成式の例もある。
code:python
logistic_map = lambda x, _: r * x * (1 - x)
r = 3.8
x0 = 0.4
inputs = repeat(x0, 36) # only the initial value is used
format(x, '.2f') for x in accumulate(inputs, logistic_map)
['0.40', '0.91', '0.30', '0.81', '0.60', '0.92', '0.29', '0.79', '0.63',
'0.88', '0.39', '0.90', '0.33', '0.84', '0.52', '0.95', '0.18', '0.57',
'0.93', '0.25', '0.71', '0.79', '0.63', '0.88', '0.39', '0.91', '0.32',
'0.83', '0.54', '0.95', '0.20', '0.60', '0.91', '0.30', '0.80', '0.60']
練習記録
collection_itertools.ipynb - Colaboratory
参考
erikrose/more-itertools: More routines for operating on iterables, beyond itertools
このあたり、自分で作れるようにならないとあるけど、、、さっと作れないので、便利。
Python pandas アクセサ / Grouperで少し高度なグルーピング/集計 - StatsFragments
#python