反復可能オブジェクトが添字付けできない場合もあります。 からの戻り値を考えてみましょうitertools.permutations
:
ps = permutations(range(10), 10)
print ps[1000]
Pythonは次のように文句を言う'itertools.permutations' object is not subscriptable
もちろん、 n 番目の要素を取得するために、 next()
byn
回実行することもできます。 もっと良い方法はあるのでしょうか?
ベストアンサー1
nth
レシピを使うだけitertools
>>> from itertools import permutations, islice
>>> def nth(iterable, n, default=None):
"Returns the nth item or a default value"
return next(islice(iterable, n, None), default)
>>> print nth(permutations(range(10), 10), 1000)
(0, 1, 2, 4, 6, 5, 8, 9, 3, 7)