Python - Generator生成器( yield )

版权声明:转载请注明出处 https://blog.csdn.net/qq_42292831/article/details/88824773

带有 yield 的函数在 Python 中被称之为 generator(生成器) 



yield 的作用就是把一个函数变成一个 generator,带有 yield 的函数不再是一个普通函数,Python 解释器会将其视为一个 generator,调用 fab(5) 不会执行 fab 函数,而是返回一个 iterable 对象!

在 for 循环执行时,每次循环都会执行 fab 函数内部的代码,执行到 yield b 时,fab 函数就返回一个迭代值,下次迭代时,代码从 yield b 的下一条语句继续执行,而函数的本地变量看起来和上次中断执行前是完全一样的,于是函数继续执行,直到再次遇到 yield。

* 在python3.x版本中,next()被替换为__next__()

* 与此类似采用Generator原理的xrange()也在python3.x中更名为range()



Example:遍历无限的数字+字母标识序列,从1a-1z,然后2a-2z,以此类推 

# -*- coding: utf-8 -*-
"""
Created on Tue Mar 26 15:52:50 2019
@author: dell
alphabet:字母表
"""

import string

def alphabet_circle():
    n = 1
    while True:
        for c in string.ascii_lowercase:
            yield str(n)+c
        n+=1

a = alphabet_circle()
#Generator
print(a)    
#use __next__() to get next element
print(a.__next__())
print(a.__next__())
print(a.__next__())


if __name__=="__main__":
    for c in a:
        print(c)

猜你喜欢

转载自blog.csdn.net/qq_42292831/article/details/88824773
今日推荐