For loop iterate over powers of 2

前端 未结 5 798
醉话见心
醉话见心 2021-01-28 16:55

I want to write a for loop that will iterate over the powers of 2 for each loop.

For example I would want a range like this:

2, 4, 8, 16, ... , 1024
         


        
5条回答
  •  礼貌的吻别
    2021-01-28 17:46

    You can use a generator expression so that it generates the numbers as needed and they don't waste memory:

    >>> for x in (2**p for p in range(1, 11)):
    ...    print(x)
    
    2
    4
    8
    16
    32
    64
    128
    256
    512
    1024
    

    In Python 2, you can use xrange instead of range to keep it as a generator and avoid creating unnecessary lists.

    If you want to enter the actual stop point instead of the power to stop at, this is probably the simplest way:

    from itertools import count
    for x in (2**p for p in count(1)):
        if x > 1024:
            break
        print(x)
    

    You could put it all in one line:

    from itertools import count, takewhile
    for x in takewhile(lambda x: x <= 1024, (2**p for p in count(1))):
        print(x)
    

    but that's becoming silly (and not very readable).

提交回复
热议问题