pyDay10

内容来自雪峰的官方网站。

1、python的赋值语句:a, b, c = x, y, z 相当于 a = x, b = y, c = z。(事实上等式右边是一个tuple)

2、获得genarator的第二种方式。

示例一:

def fib(max):
    n, a, b = 0, 0, 1
    while n < max:
        yield b
        a, b = b, a + b
        n = n + 1
    return 'done'

示例二:

def odd():
    print('step 1')
    yield 1
    print('step 2')
    yield 3
    print('step 3')
    yield 5

 generator在执行过程中,遇到yield就中断,下次又继续执行。

3、调用该generator时,首先要生成一个generator对象,然后用next()函数不断获得下一个返回值。

 调用示例一:

>>> o = odd()
>>> next(o)
step 1
1
>>> next(o)
step 2
3
>>> next(o)
step 3
5
>>> next(o)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

 调用示例二:

>>> f = fib(6)
>>> for n in fib(6):
...     print(n)
...
1
1
2
3
5
8
原文地址:https://www.cnblogs.com/xkxf/p/6424886.html