无限的序列
生成器可用于表示无限序列:
def integers_starting_from(n):
while True:
yield n
n += 1
natural_numbers = integers_starting_from(1)
如上所述的无限数字序列也可以在 itertools.count
的帮助下生成 。上面的代码可以写成如下
natural_numbers = itertools.count(1)
你可以在无限生成器上使用生成器理解来生成新生成器:
multiples_of_two = (x * 2 for x in natural_numbers)
multiples_of_three = (x for x in natural_numbers if x % 3 == 0)
请注意,无限生成器没有结束,因此将其传递给将尝试完全使用生成器的任何函数将产生可怕的后果 :
list(multiples_of_two) # will never terminate, or raise an OS-specific error
相反,使用 list / set comprehensions with range
(或 xrange
for python <3.0):
first_five_multiples_of_three = [next(multiples_of_three) for _ in range(5)]
# [3, 6, 9, 12, 15]
或使用 itertools.islice()
将迭代器切片为子集:
from itertools import islice
multiples_of_four = (x * 4 for x in integers_starting_from(1))
first_five_multiples_of_four = list(islice(multiples_of_four, 5))
# [4, 8, 12, 16, 20]
请注意,原始生成器也会更新,就像来自同一根的所有其他生成器一样:
next(natural_numbers) # yields 16
next(multiples_of_two) # yields 34
next(multiples_of_four) # yields 24
无限序列也可以用 for
循环迭代。确保包含条件 break
语句,以便循环最终终止:
for idx, number in enumerate(multiplies_of_two):
print(number)
if idx == 9:
break # stop after taking the first 10 multiplies of two
经典例子 - 斐波纳契数
import itertools
def fibonacci():
a, b = 1, 1
while True:
yield a
a, b = b, a + b
first_ten_fibs = list(itertools.islice(fibonacci(), 10))
# [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
def nth_fib(n):
return next(itertools.islice(fibonacci(), n - 1, n))
ninety_nineth_fib = nth_fib(99) # 354224848179261915075