在Python中获取生成器的第n个项 [英] Get the nth item of a generator in Python

查看:64
本文介绍了在Python中获取生成器的第n个项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有语法上更简洁的方式编写以下内容?

Is there a more syntactically concise way of writing the following?

gen = (i for i in xrange(10))
index = 5
for i, v in enumerate(gen):
    if i is index:
        return v

生成器应该具有gen[index]表达式作为列表,但这在功能上与上述代码相同,这似乎是很自然的.

It seems almost natural that a generator should have a gen[index] expression, that acts as a list, but is functionally identical to the above code.

推荐答案

一种方法是使用 itertools.islice

one method would be to use itertools.islice

>>> gen = (x for x in range(10))
>>> index = 5
>>> next(itertools.islice(gen, index, None))
5

这篇关于在Python中获取生成器的第n个项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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