有时一个可迭代对象可能是不可下标的。说出 itertools.permutations
的返回:
ps = permutations(range(10), 10)
print ps[1000]
Python 会提示 'itertools.permutations' 对象不可下标
当然可以执行next()
n
次来获得第n 个元素。只是想知道有没有更好的方法呢?
最佳答案
只需使用 itertools
中的 nth
配方
>>> 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)
关于python - 从不可下标的可迭代对象中获取第 n 个元素的更好方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12007820/