欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Python yield的简单应用和理解(代码)

程序员文章站 2022-05-03 19:33:36
Python yield的简单应用和理解(代码) # coding=utf-8 from random import randint def rand_gen(a...

Python yield的简单应用和理解(代码)

# coding=utf-8
from random import randint


def rand_gen(aList):
    while len(aList) > 0:
        yield aList.pop(randint(0, len(aList)-1))


def counter(start_at=0):
    count = start_at
    while True:
        # 第一次val等于yield的返回值,随后因为while的存在yield没有返回值,yield返回None
        # 随后count被加一, yield再次有值可以返回
        val = (yield count)
        if val is not None:
            count = val
        else:
            count += 1


for item in rand_gen(['rock', 'paper', 'scissors']):
    print item

count = counter(5)
print count.next()      # 5
print count.next()      # 6
print count.send(9)     # 9
print count.next()      # 10
print count.close()     # None