Heim  >  Artikel  >  Backend-Entwicklung  >  python生成器的使用方法

python生成器的使用方法

WBOY
WBOYOriginal
2016-06-16 08:46:101146Durchsuche

什么是生成器?

生成器是一个包含了特殊关键字yield的函数。当被调用的时候,生成器函数返回一个生成器。可以使用send,throw,close方法让生成器和外界交互。

生成器也是迭代器,但是它不仅仅是迭代器,拥有next方法并且行为和迭代器完全相同。所以生成器也可以用于python的循环中,

生成器如何使用?

首先看一个例子:

复制代码 代码如下:

#!/usr/bin/python
# -*- coding: utf-8 -*-

def flatten(nested):
    for sublist in nested:
        for element in sublist:
            yield element

nested = [[1,2],[3,4],[5,6]]

for num in flatten(nested):
    print num,

结果为1,2,3,4,5,6

递归生成器:

复制代码 代码如下:

#!/usr/bin/python
# -*- coding: utf-8 -*-

def flatten(nested):
    try:
        for sublist in nested:
            for element in flatten(sublist):
                yield  element
    except TypeError:
        yield nested

for num in flatten([[1,2,3],2,4,[5,[6],7]]):
    print num

结果为:1 2 3 2 4 5 6 7

让我们一起来看看生成器的本质

首先看下:

复制代码 代码如下:

#!/usr/bin/python
# -*- coding: utf-8 -*-

def simple_generator():
    yield 1

print simple_generator

def repeater(value):
    while True:
        new  = (yield value)
        if new is not None: value = new


r = repeater(42)
print r.next()

print r.send('hello,world!')

结果为:

复制代码 代码如下:


42
hello,world!

可以看出:
1)生成器就是一函数
2)生成器具有next方法
3)生成器可以使用send 方法和外界交互。

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn