1000字范文,内容丰富有趣,学习的好帮手!
1000字范文 > python generator类型_python生成器(Generator)

python generator类型_python生成器(Generator)

时间:2019-07-10 12:58:37

相关推荐

python generator类型_python生成器(Generator)

生成器是一种特殊的迭代器,它提供了自定义迭代器的一种方式。生成器最牛逼的特点就是对延迟操作的支持,一次只返回一个结果,然后状态挂起,以便下次从此状态开始继续执行。

python中有两种类型的生成器:生成器函数和生成器表达式。

生成器函数

先看一下官方定义:A function which returns an iterator. It looks like a normal function except that it contains yield statements for producing a series a values usable in a for-loop or that can be retrieved one at a time with the next() function.

简单说,生成器函数是在函数体中存在yield关键字的函数。对,只是存在就足够使一个函数成为生成器函数了。

>>> def gen():

... yield

...

>>> g = gen()

>>> g

>>> print(next(g))

None

>>> dir(g)

['__class__', '__delattr__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__iter__', '__name__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'close', 'gi_code', 'gi_frame', 'gi_running', 'next', 'send', 'throw']

在看一个稍正常点的例子:

>>> def gen1():

... x = 1

... yield x

... x += 1

... yield x

... x += 3

... yield x

...

>>> g = gen1()

>>> print(next(g))

1

>>> print(next(g))

2

>>> print(next(g))

5

>>> print(next(g))

Traceback (most recent call last):

File "", line 1, in

StopIteration

由于生成器本身就是迭代器,所以只能遍历一次。有一种方法可以定义可重用的生成器,就是定义一个基于对象的生成器。任何在__iter__

方法中通过yield返回数据的类都可以用作对象生成器,注意是用作生成器,它并不是生成器。

>>> class counter(object):

... def __init__(self, a, b):

... self.a = a

... self.b = b

... def __iter__(self):

... num = self.a

... while self.b >= num:

... yield num

... num += 1

...

>>> c = counter(1, 3)

>>> for i in c:

... print i

...

1

2

3

>>> for i in c:

... print i

...

1

2

3

生成器表达式

生气表达式有一个比较经典的例子:

列表推导式(list comprehension)

>>> numbers = [1, 2, 3, 4, 5, 6]

>>> [x*x for x in numbers]

[1, 4, 9, 16, 25, 36]

集合推导式(set comprehension)

>>> {x*x for x in numbers}

set([1, 36, 9, 16, 25, 4])

字典推导式(dict comprehension)

>>> {x:x*x for x in numbers}

{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36}

生成器表达式呢,就是下面这样的(注意:这不是元组推导式(tuple comprehension),python中没有tuple comprehension)。

>>> gen = (x * x for x in numbers)

>>> gen

at 0x10a351b90>

>>> next(gen)

1

>>> list(gen)

[4, 9, 16, 25, 36]

其实,列表推导式,集合推导式和字典推导式都只是语法糖,它们都是使用生成器输出特定的类型而已。

(从python 2.5以后,添加了基于生成器构建的并发框架--协程)

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。