Reputation: 1933
Say I want to create a list using list comprehension like:
l = [100., 50., 25., 12.5, ..., a_n]
…i.e., 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.
Upvotes: 6
Views: 3302
Reputation: 51
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)
Upvotes: 1
Reputation: 508
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]
Upvotes: 1
Reputation: 8569
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
Upvotes: 5
Reputation: 81594
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]
Upvotes: 5