简体   繁体   中英

List comprehension using while loop?

Is there a way to use a while loop in a list comprehension.

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)

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. For example

example 1, with 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

>>> 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

the point of divergence is very easy to found (using the above 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...

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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