Python 生成器 yield
2012-04-09 16:24
399 查看
Example1:
def fibonacci():
a, b = 0, 1
while True:
print 'abc'
yield b
a, b = b, a+b
fib = fibonacci()
fib.next()
[fib.next() for i in range(10)] #感觉这种写法很精妙
Example 2: yield 作为表达式 Send 来填充 yield表达式,throw 抛出异常,close抛出GeneratorExit异常
def psychologist():
print 'Please tell me your problems'
while True:
answer = yield
if answer is not None:
pass
if answer.endswith('?'):
print("Don't ask yourself too much questions")
elif 'good' in answer:
print('A that\'s good,go on')
elif 'bad' in answer:
print('Don\'t be so negative')
free = psychologist()
free.next()
free.send('I feel bad')
free.send('I feel good')
>>> Please tell me your problems
Don't be so negative
A that's good,go on
def myGenerator():
try:
yield 'something'
except ValueError:
yield 'dealing with the exception'
finally:
print 'ok let\'s clean'
gen = myGenerator()
gen.next()
gen.throw(ValueError('abcde'))
gen.close()
>>> something
dealing with the exception
ok let's clean
def fibonacci():
a, b = 0, 1
while True:
print 'abc'
yield b
a, b = b, a+b
fib = fibonacci()
fib.next()
[fib.next() for i in range(10)] #感觉这种写法很精妙
Example 2: yield 作为表达式 Send 来填充 yield表达式,throw 抛出异常,close抛出GeneratorExit异常
def psychologist():
print 'Please tell me your problems'
while True:
answer = yield
if answer is not None:
pass
if answer.endswith('?'):
print("Don't ask yourself too much questions")
elif 'good' in answer:
print('A that\'s good,go on')
elif 'bad' in answer:
print('Don\'t be so negative')
free = psychologist()
free.next()
free.send('I feel bad')
free.send('I feel good')
>>> Please tell me your problems
Don't be so negative
A that's good,go on
def myGenerator():
try:
yield 'something'
except ValueError:
yield 'dealing with the exception'
finally:
print 'ok let\'s clean'
gen = myGenerator()
gen.next()
gen.throw(ValueError('abcde'))
gen.close()
>>> something
dealing with the exception
ok let's clean
相关文章推荐
- Python 3 中生成器函数yield表达式的使用
- Python基础-迭代器与yield生成器
- Python Generators(生成器)——yield关键字
- python yield生成器
- 零基础学python-19.5 重访迭代器:生成器yield
- 举例详解Python中yield生成器的用法
- Python Generators(生成器)——yield关键字
- 每日一题_Python.利用yield生成器实现协程下的tps透明传输CS测试
- python-yield-生成器--的作用
- yield生成器对象返回Fiabs元素 分类: python 小练习 python基础学习 2014-01-13 10:28 193人阅读 评论(0) 收藏
- Python Generators(生成器)——yield关键字
- python生成器:使用yield关键字定义迭代器
- python中的yield生成器详解
- Python生成器&__iter__&yield
- 举例详解Python中yield生成器的用法
- python的生成器与yield
- Python中的yield和Generators(生成器)
- python yield和generators(生成器)
- python中的yield生成器详解
- Python生成器与yield