如何循环通过发电机 [英] How to loop through a generator

查看:78
本文介绍了如何循环通过发电机的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个发电机如何循环?我是这样想的:

How can one loop through a generator? I thought about this way:

gen = function_that_returns_a_generator(param1, param2)
if gen: # in case the generator is null
    while True:
        try:
            print gen.next()
        except StopIteration:
            break

还有更Python化的方式吗?

Is there a more pythonic way?

推荐答案

简单

for x in gen:
    # whatever

可以解决问题.请注意,if gen始终返回True.

will do the trick. Note that if gen always returns True.

这篇关于如何循环通过发电机的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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