从unsubscriptable iterable中获取第n个元素的更好方法 [英] Better ways to get nth element from an unsubscriptable iterable

查看:136
本文介绍了从unsubscriptable iterable中获取第n个元素的更好方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有时,iterable可能不是可订阅的。假设从返回

Sometimes an iterable might be not subscriptable. Say the return from itertools.permutations:

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

Python会抱怨'itertools.permutations'对象不可订阅

Python will complain that 'itertools.permutations' object is not subscriptable

当然可以执行 next() n 获取第n个元素的次数。只是想知道有更好的方法吗?

Of course one can perform next() by n times to get the nth element. Just wondering are there better ways to do so?

推荐答案

只需使用 nth 来自 itertools 的食谱

Just use nth recipe from 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)

这篇关于从unsubscriptable iterable中获取第n个元素的更好方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆