Amazing Python 1: "yield"

"yield" is used for Generater (below 2.2) or seperately (2.2 or above) in Python.


"yield" mainly works as "return", but it makes a function able to have multiple return values step by step .

All return values will comprise a sequence which can be used in "for" or more amazingly as a "link" by running "link.next()"!

 

Example 1:

def generater():
    yield 1
    yield 2
    yield 3
    
for i in generater():
    print i,
print "\n"

print "getnerater() =", generater() 
print "list(generater()) =", list(generater())
print

link = generater()
print "link.next() =", link.next()
print "link.next() =", link.next()
print "link.next() =", link.next()

Output:

1 2 3 

getnerater() = <generator object at 0xb7dafb0c>
list(generater()) = [1, 2, 3]

link.next() = 1
link.next() = 2
link.next() = 3


Example2, calculating fibonacci(20):

(from speech "Object-oriented design with Python" by Bruce Eckel, 2005, http://us.pycon.org/talks/2005/wed/track1/44/talkDetails )

def fibonacci(count):
    def fib(n):
        if n < 2: return 1
        return fib(n-2) + fib(n-1)
    n = 0
    while n < count:
        yield fib(n)
        n += 1

for f in fibonacci(20): # Automatically iterable
    print f,

Output:

1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 

 

Example3, let's forget about recursion!

(from "Dive into Python, e.g. 17.19")

def fibonacci(n):
    a, b = 1, 1
    for i in range(n):
        yield a 
        a, b = b, a+b

for f in fibonacci(20):
    print f,

Output:

1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值