Home > Backend Development > Python Tutorial > Python yield 小结和实例

Python yield 小结和实例

WBOY
Release: 2016-06-16 08:44:25
Original
922 people have browsed it

一个带有 yield 的函数就是一个 generator,它和普通函数不同,生成一个 generator 看起来像函数调用,但不会执行任何函数代码,直到对其调用 next()(在 for 循环中会自动调用 next())才开始执行。虽然执行流程仍按函数的流程执行,但每执行到一个 yield 语句就会中断,并返回一个迭代值,下次执行时从 yield 的下一个语句继续执行。看起来就好像一个函数在正常执行的过程中被 yield 中断了数次,每次中断都会通过 yield 返回当前的迭代值。

yield 的好处:把一个函数改写为一个 generator 就获得了迭代能力,比起用类的实例保存状态来计算下一个 next() 的值,不仅代码简洁,而且执行流程异常清晰。

测试代码:
 

复制代码 代码如下:

#!/usr/bin/env python
#-*- coding:utf8 -*-

def fab(max):
    """斐波那契數列"""
    n, a, b = 0, 0, 1
    while n         yield b
        a, b = b, a + b
        n += 1


def perm(items, n=None):
    """全排列"""
    if n is None:
        n = len(items)
    for i in range(len(items)):
        v = items[i:i+1]
        if n == 1:
            yield v
        else:
            rest = items[:i] + items[i+1:]
            for p in perm(rest, n-1):
                yield v + p

if __name__ == '__main__':
    for n in fab(5):
        print n
    print  "全排列:123"
    for n in perm("123"):
        print n

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template