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
如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!