简体   繁体   中英

Python: list comprehension based on previous value?

Say I want to create a list using list comprehension like:

l = [100., 50., 25., 12.5, ..., a_n]

…ie, start with some number and generate the n "halves" from that in the same list. I might either be missing some straightforward pythonic way of doing that, or I'll simply have to rely on a good ol' for-loop. Can this be done? Thanks.

How about this?

start = 2500.0
n = 50
halves = [start / 2.0**i for i in range(n)]

equal to this:

[start * 2.0**(-i) for i in range(n)]

probably less efficient in contrast to @DeepSpace's answer but a one-liner

Define a generator, and use it in the list comprehension:

def halve(n):
    while n >= 1:
        yield n
        n /= 2

print([_ for _ in halve(100)])
>> [100, 50.0, 25.0, 12.5, 6.25, 3.125, 1.5625]

Or simply convert it to a list:

print(list(halve(100)))
>> [100, 50.0, 25.0, 12.5, 6.25, 3.125, 1.5625]

EDIT In case @R Nar's comment is correct:

def halve(start, n):
    for _ in range(n):
        yield start
        start /= 2

print(list(halve(100, 3)))
>> [100, 50.0, 25.0]

print(list(halve(100, 4)))
>> [100, 50.0, 25.0, 12.5]

Try this (Python 3.8.5):

from itertools import accumulate 

n=5
result = list(accumulate(range(n), lambda acc, val: acc/2, initial=100))
print(result)

The following code works with int but not floats.

[100>>i for i in range(10)]

this returns:

[100, 50, 25, 12, 6, 3, 1, 0, 0, 0]

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