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

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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值