如何编写一行代码,在 python 中使用生成器斐波那契打印

How to write one line of code that prints with generator fibonacci in python

我在打印和生成器方面遇到问题。我需要:

In addition to the above generators, write one line of code that prints the list of all the numbers (which is different from "all the numbers") that are less than 1000 and also divisible by 3 in the Fibonacci sequence, starting with 0, 1

我的发电机:

def fibonacci(x,y):
    a, b= x, y
    while True:
        yield a
        a, b = b, a + b

def fibonacci_until(x,y,n):
    a, b = x, y
    while b <=n:
        yield a
        a, b = b, a + b

我的尝试:

print([for f in fibonacci(0,1) if ((f % 3) == 0) and (f<1000)])

好的,你需要这样修改:

def fibonacci_until(x,y,n):
    a, b = x, y
    while b <=n:
        yield a
        a, b = b, a + b

print([f for f in fibonacci_until(0,1, 1000) if ((f % 3) == 0)])

你的数组生成错误,也应该使用不会无限运行的方法:)

你可以用你的 fibonacci_until 生成器做到这一点,

[f for f in fibonacci_until(0,1, 1000) if f % 3 == 0]