简体   繁体   English

使用while循环进行列表理解?

[英]List comprehension using while loop?

Is there a way to use a while loop in a list comprehension.有没有办法在列表理解中使用 while 循环。

For example, I have a single line Fibonacci generator:例如,我有一个单行斐波那契生成器:

[int(((1+(5**0.5))**n-(1-(5**0.5))**n)/(2**n*(5**0.5))) for n in range(100)]

but I'd like it to stop at a certain outcome, rather than just run a certain number of times.但我希望它在某个结果处停止,而不仅仅是运行一定次数。 (ie all Fibonacci sequence numbers below 4,000,000) (即所有低于 4,000,000 的斐波那契数列)

This is a question about list-comprehension, not about lists in general.这是一个关于列表理解的问题,而不是一般的列表。

The more generic phrasing might be this:更通用的措辞可能是这样的:

[(formula using incrementing variable) 
    for incrementing variable while (result is less than specified amount)]

python don't have such feature of using while in a comprehension (which is like a map combined with filter), but you can accomplished that using other tools like making a function that do what you desire or using your best friend the itertools module. python 没有在理解中使用while功能(就像地图与过滤器相结合),但是您可以使用其他工具来实现这一点,例如制作一个可以做您想要的功能或使用您最好的朋友itertools模块。 For example例如

example 1, with itertools示例 1,使用 itertools

>>> from itertools import takewhile
>>> def fib():
        fk,fk1 = 0,1
        while True:
            yield fk
            fk, fk1 = fk1, fk + fk1


>>> list(takewhile(lambda fn:fn<100,fib()))
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
>>> 

example 2, with a function例子2,带函数

>>> def fib_while(tope):
        fk,fk1 = 0,1
        while fk < tope:
            yield fk
            fk,fk1 = fk1, fk + fk1


>>> list(fib_while(100))
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
>>>    

oh, I forgot to mention, but your formula for getting the Fibonacci numbers, even if mathematical correct, is doom to fail to get the real value for a large enough n, because floating point arithmetic rounding errors哦,我忘了提,但是您获取斐波那契数的公式,即使数学正确,也注定无法获得足够大的 n 的真实值,因为浮点算术舍入错误

the point of divergence is very easy to found (using the above fib )分歧点很容易找到(使用上面的fib

>>> def fib_float(n):
        return int(((1+(5**0.5))**n-(1-(5**0.5))**n)/(2**n*(5**0.5)))

>>> [n for n,f in zip(range(100),fib()) if f!=fib_float(n)] )
[72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]
>>>

so for all n>=72 what you get are not Fibonacci numbers...所以对于所有 n>=72 你得到的不是斐波那契数...

if you only care for all numbers in the sequence below 4,000,000 then that is not a problem of course as the limit is n=33如果您只关心序列中 4,000,000 以下的所有数字,那么这当然不是问题,因为限制是 n=33

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM