#!/usr/bin/python3
import sys
def fibonacci(n,w=0): # 生成器函数 - 斐波那契
a, b, counter = 0, 1, 0
while True:
if (counter > n):
return
yield a
a, b = b, a + b
print('%d,%d' % (a,b))
counter += 1
f = fibonacci(10,0) # f 是一个迭代器,由生成器返回生成
while True:
try:
print (next(f), end=" ")
except :
sys.exit()
#!/usr/bin/python3
import sys
def fibonacci(n,w=0): # 生成器函数 - 斐波那契
a, b, counter = 0, 1, 0
while True:
if (counter > n):
return
#yield a
a, b = b, a + b
print('%d,%d' % (a,b))
counter += 1
f = fibonacci(10,0) # f 是一个迭代器,由生成器返回生成
while True:
try:
print (next(f), end=" ")
except :
sys.exit()
>>> l = [i for i in range(0,15)]
>>> print(l)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
>>> m = (i for i in range(0,15))
>>> print(m)
<generator object <genexpr> at 0x104b6f258>
>>> for g in m:
... print(g,end=', ')
...
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
一个函数 f,f 返回一个 list,这个 list 是动态计算出来的(不管是数学上的计算还是逻辑上的读取格式化),并且这个 list 会很大(无论是固定很大还是随着输入参数的增大而增大),这个时候,我们希望每次调用这个函数并使用迭代器进行循环的时候一个一个的得到每个 list 元素而不是直接得到一个完整的 list 来节省内存,这个时候 yield 就很有用。
def myYield_1():
a, i = 'yield', 0
while True:
print('before #%d' % i, end=", ")
yield a, i
print('after #%d' % i, end=", ")
i += 1
def myYield_2():
a, i = 'yield_a', 0
b, i = 'yield_b', 0
while True:
print('before #%d' % i, end=", ")
yield a, i
yield b, i
print('after #%d' % i, end=", ")
i += 1
it1 = iter(myYield_1())
it2 = iter(myYield_2())
for i in range(10):
print("next #%d" % i, end=": ")
print(next(it1))
print('\n')
for i in range(10):
print("next #%d" % i, end=": ")
print(next(it2))
输出是这样的:
next #0: before #0, ('yield', 0)
next #1: after #0, before #1, ('yield', 1)
next #2: after #1, before #2, ('yield', 2)
next #3: after #2, before #3, ('yield', 3)
next #4: after #3, before #4, ('yield', 4)
next #5: after #4, before #5, ('yield', 5)
next #6: after #5, before #6, ('yield', 6)
next #7: after #6, before #7, ('yield', 7)
next #8: after #7, before #8, ('yield', 8)
next #9: after #8, before #9, ('yield', 9)
next #0: before #0, ('yield_a', 0)
next #1: ('yield_b', 0)
next #2: after #0, before #1, ('yield_a', 1)
next #3: ('yield_b', 1)
next #4: after #1, before #2, ('yield_a', 2)
next #5: ('yield_b', 2)
next #6: after #2, before #3, ('yield_a', 3)
next #7: ('yield_b', 3)
next #8: after #3, before #4, ('yield_a', 4)
next #9: ('yield_b', 4)
yield a: yield 是 Python 中一个非常有用的关键字,它用于定义生成器函数并返回生成器对象。当生成器函数执行到 yield 关键字时,它将将当前函数状态保存为暂停状态,并向调用方返回一个值 a,之后程序流程将被挂起,直到下次通过 next() 函数调用该生成器对象时再恢复执行状态。在斐波那契数列生成器函数中,每次执行到 yield a 时,都会生成当前数列的第一个数字 a 并返回给调用方。
a, b = b, a + b: 这是 Python 中的一种元组赋值语法,可以同时将多个变量赋值为多个值。在斐波那契数列生成器函数中,这行代码的作用是更新相邻两个数字 a 和 b 的值,以便生成下一个斐波那契数。首先,变量 a 被赋值为变量 b 的值,表示将上一个斐波那契数列中的第二个数字赋值为下一个数列的第一个数字;然后,变量 b 被赋值为表达式 a + b 的值,表示将上一个斐波那契数列中的前两个数字相加得到下一个数列中的第二个数字。这样,在每次执行 yield a 之前,都会先更新 a 和 b 的值,从而生成下一个斐波那契数。
You are visitor 01402775 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.