添字付けできない反復可能オブジェクトから n 番目の要素を取得するより良い方法 質問する

添字付けできない反復可能オブジェクトから n 番目の要素を取得するより良い方法 質問する

反復可能オブジェクトが添字付けできない場合もあります。 からの戻り値を考えてみましょう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)

おすすめ記事