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

Mor*_*ock 1 python generator while-loop

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

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

这种while方法有什么不对或可以改进的吗?有没有办法避免在循环之前分配'c'?

谢谢!

Dan*_*l G 7

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

a = ["Hello", "world", "!"]
b = (x for x in a)
for c in b:
    print c,
Run Code Online (Sandbox Code Playgroud)

如果你while出于某种原因坚持实施,你当前的实施可能是你能做的最好的,但它有点笨重,你不觉得吗?