From Python 初学者:
from itertools import islice
def fib():
prev, curr = 0, 1
count = 0
while True:
print("pause",count,end=" ")
count += 1
yield curr
prev, curr = curr, prev + curr
print("pause",count,end=" ")
count += 1
f = fib()
for x in islice(f, 0, 10):
print(x)
pause 0 1
pause 1 pause 2 1
pause 3 pause 4 2
pause 5 pause 6 3
pause 7 pause 8 5
pause 9 pause 10 8
pause 11 pause 12 13
pause 13 pause 14 21
pause 15 pause 16 34
pause 17 pause 18 55
def something():
result = []
for ... in ...:
result.append(x)
return result
"""
可改为
"""
def iter_something():
for ... in ...:
yield x
# def something(): # Only if you really need a list structure
# return list(iter_something())