python程序中yield用法。

看了好多关于yield说明,实在是搞不懂怎么用的。于是自己动手写代码。终于明白了。

def ytest(data):
    a,b = 1,2
    while a < data:
        yield b
        a = a + 1

def ytest2(data):
    a,b = 1,2
    while a < data:
        yield a
        a = a + 1

if __name__ == "__main__":
    print("start ytest")
    for c in ytest(4):
        print(c)
    print("start ytest2")
    for c in ytest2(4):
        print(c)

运行结果:

start ytest
2
2
2
start ytest2
1
2
3


看明白没有,迭代返回的结果基本就是yield后面的内容。原理网上太多,自己看分析。用法如此简单而已。


此文讲原理很清楚。

http://www.jb51.net/article/15717.htm

猜你喜欢

转载自blog.csdn.net/Blaider/article/details/50827954
今日推荐