从unsubscriptable iterable中获取第n个元素的更好方法

clw*_*wen 20 python iterator

有时,iterable可能不是可订阅的.说来自itertools.permutations:

ps = permutations(range(10), 10)
print ps[1000]
Run Code Online (Sandbox Code Playgroud)

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

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

jam*_*lak 28

只需使用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)
Run Code Online (Sandbox Code Playgroud)

  • 这是一件美好的事情.(1) (2认同)