这可能是学习生成器的一个很好的例子。生成器看起来像一个普通函数,它使用yield
而不是return
. 不同之处在于,当使用生成器函数时,它表现为一个可迭代对象,产生一系列值。尝试以下操作:
#!python3
def gen():
for x in range (1, 21):
if x % 15 == 0:
yield "fizzbuzz"
elif x % 5 == 0:
yield "buzz"
elif x % 3 == 0:
yield "fizz"
else:
yield str(x)
# Now the examples of using the generator.
for v in gen():
print(v)
# Another example.
lst = list(gen()) # the list() iterates through the values and builds the list object
print(lst)
# And printing the join of the iterated elements.
print(','.join(gen())) # the join iterates through the values and joins them by ','
# The above ','.join(gen()) produces a single string that is printed.
# The alternative approach is to use the fact the print function can accept more
# printed arguments, and it is possible to set a different separator than a space.
# The * in front of gen() means that the gen() will be evaluated as iterable.
# Simply said, print can see it as if all the values were explicitly writen as
# the print arguments.
print(*gen(), sep=',')
请参阅http://docs.python.org/3/library/functions.html#printprint
处的函数参数的文档,并在http://docs.python.org/3/reference/expressions.html#*expression
处调用参数来电。
最后一种方法的另一个优点print
是参数不必是字符串类型。gen()
显式使用定义str(x)
而不是普通定义的原因x
是因为.join()
要求所有连接的值都必须是字符串类型。在print
内部将所有传递的参数转换为字符串。如果gen()
使用 plain yield x
,并且您坚持使用连接,则join
可以使用生成器表达式即时将参数转换为字符串:
','.join(str(x) for x in gen()))
它显示在我的控制台上:
c:\tmp\___python\JessicaSmith\so18500305>py a.py
1
2
fizz
4
buzz
fizz
7
8
fizz
buzz
11
fizz
13
14
fizzbuzz
16
17
fizz
19
buzz
['1', '2', 'fizz', '4', 'buzz', 'fizz', '7', '8', 'fizz', 'buzz', '11', 'fizz',
'13', '14', 'fizzbuzz', '16', '17', 'fizz', '19', 'buzz']
1,2,fizz,4,buzz,fizz,7,8,fizz,buzz,11,fizz,13,14,fizzbuzz,16,17,fizz,19,buzz
1,2,fizz,4,buzz,fizz,7,8,fizz,buzz,11,fizz,13,14,fizzbuzz,16,17,fizz,19,buzz