从不可订阅的迭代中获取第n个元素的更好方法


问题内容

有时,迭代可能无法下标。说出来自的回报itertools.permutations

ps = permutations(range(10), 10)
print ps[1000]

Python会抱怨 'itertools.permutations' object is not subscriptable

当然,一个可以执行next()n时间来获得的第n个元素。只想知道还有更好的方法吗?


问题答案:

只需使用以下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)