python - 从不可下标的可迭代对象中获取第 n 个元素的更好方法

标签 python iterator

有时一个可迭代对象可能是不可下标的。说出 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/

相关文章:

python - 使用 Python 将数组与从 mysql 数据库返回的值进行比较

python - 在 Python 中取消定时器

c++ - UTF-8 字符串迭代器

python - StopIteration 异常是否会自动通过我的迭代器向上传播?

java - Java 中传统 for 循环与 Iterator/foreach 的性能对比

python - 从列表字典创建 n 个嵌套循环

python - Sublime如何循环完成?

php - PHP下如何调用python脚本文件?

python - 将 Cassandra OrderedMapSerializedKey 转换为 Python 字典

jsp - Struts 2 嵌套迭代器