您的位置:首页 > 编程语言 > Python开发

Python yield的简单应用和理解

2018-02-10 21:13 337 查看
# 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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: