Skip to main content
 首页 » 编程设计

python之如何正确定义和使用 Python 生成器

2025年05月04日10dflying

我想从一个列表中定义一个生成器,一次输出一个元素,然后以适当的方式使用这个生成器对象。

a = ["Hello", "world", "!"] 
b = (x for x in a) 
c = next(b, None) 
while c != None: 
    print c, 
    c = next(b, None) 

这里的 while 方法有什么错误或可以改进的地方吗?有没有办法避免在循环之前分配“c”?

谢谢!

请您参考如下方法:

为什么要使用 while 循环?在 Python 中,for 循环绝对是为此设计的:

a = ["Hello", "world", "!"] 
b = (x for x in a) 
for c in b: 
    print c, 

如果您出于某种原因卡在 while 实现上,您当前的实现可能是您能做的最好的,但它有点笨拙,您不觉得吗?