無限的序列

生成器可用於表示無限序列:

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