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

发布于 2021-01-29 16:31:01

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

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

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

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

关注者
0
被浏览
51
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

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


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看