生成器是Python中的比较难的一个概念。需要好好琢磨一下。开始的时候接触的叫做列表生成器。对就是这么神奇的名字。我好以为只有这么一种。导致后面学的比较混乱。最近好好梳理了一下。
一. generator expression
其实这应该叫做生成器表达式。官方表达如下。
generator expression
An expression that returns an iterator. It looks like a normal expression followed by a for expression defining a loop variable, range, and an optional if expression. The combined expression generates values for an enclosing function:
大概意思就是返回一个迭代器。看起开像是一个正常的表达式。最常见的是现实就是如下
生成一个可迭代的序列但是用()
括起来。
sum(i*i for i in range(10)) # sum of squares 0, 1, 4, … 81
285
或者像是我刚学的时候见到的样子。
g=(x*x for x in range(10))
for n in g:
print n
这应该是最简单的生成器。看起来也比较好懂。
二. generator
名字就叫生成器迭代器。这多指函数。官方表达如下:
A function which returns a generator iterator. It looks like a normal function except that it contains yield expressions for producing a series of values usable in a for-loop or that can be retrieved one at a time with the next() function.
Usually refers to a generator function, but may refer to a generator iterator in some contexts. In cases where the intended meaning isn’t clear, using the full terms avoids ambiguity.
大意应该是返回一个生成器迭代器。通常内部使用了一个循环,yield表达式,并用可以使用next()
方法进行检索下一个数据项。
这应该是最普通的人们描述的生成器。
类似于
def fib(max):
n, a, b = 0, 0, 1
while n < max:
res = yield b
print(b)
a, b = b, a + b
n = n + 1
a = fib(max=5)
a.send(None) #这里需要使用send(None)启动生成器
for i in range(4):
a.__next__() #遍历a
1.while循环 当 n 小于传入值max时执行。
2.yield表达式 生成一个数字b.
3.函数可以用__next__()
方法进行遍历。
三。generator iterator
名字叫生成器迭代器。
An object created by a generator function.
Each yield temporarily suspends processing, remembering the location execution state (including local variables and pending try-statements). When the generator iterator resumes, it picks-up where it left-off (in contrast to functions which start fresh on every invocation).
大意:返回一个生成器对象。
这里其实我并清楚此处和generator的表述的区别。
按照别的说法,实例化后的生成器迭代器对象会有send(),throw(),close()
方法。但是对于函数生成器好像也有这类方法。
后事:生成器的yield在协程中发挥了较大的功效。等会写这个。
参考:python 术语表