20

有时一个可迭代对象可能是不可下标的。说返回itertools.permutations

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

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

当然,可以按次执行next()n获得第 n 个元素。只是想知道有没有更好的方法呢?

4

2 回答 2

32

只需使用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)
于 2012-08-17T14:38:48.120 回答
4

一个更具可读性的解决方案是:

next(x for i,x in enumerate(ps) if i==1000)
于 2019-01-23T18:21:38.427 回答