Given this list:
[1, 2, 4, 8, 16, 32]
I want to end up with this list:
[1, 2, 2, 3, 4, 6, 8, 12, 16, 24, 32]
To clarify, I want to transform the first list into this:
[1, X, 2, X, 4, X, 8, X, 16, X, 32]
...where X
is the average between the two preceeding/trailing numbers in the first list. The final list should start with the first value of the first list, and end with the last value of the first list.
I have this as an attempt, but of course this just overwrites the existing list with those average'd numbers. How can I weave them?
list_1 = [1, 2, 4, 8, 16, 32]
list_1 = [round((list_1[i] list_1[i 1])/2) for i in range(len(list_1)-1)]
print(list_1)
UPDATE
I guess this could work. Maybe there's a better solution?
list_1 = [1, 2, 4, 8, 16, 32]
list_2 = [round((list_1[i] list_1[i 1])/2) for i in range(len(list_1)-1)]
list_1 = sorted(list_1 list_2)
print(list_1)
CodePudding user response:
I'm not sure whether it is "better," but the following is an option (for python 3.10 due to pairwise
):
from itertools import pairwise, chain
lst = [1, 2, 4, 8, 16, 32]
means = (round(sum(pair) / 2) for pair in pairwise(lst))
output = [*chain.from_iterable(zip(lst, means)), lst[-1]] # weaving
print(output) # [1, 2, 2, 3, 4, 6, 8, 12, 16, 24, 32]
If pairwise
is not available, you can use:
means = (round(sum(pair) / 2) for pair in zip(lst, lst[1:]))
CodePudding user response:
I am assuming you need the ceiling value of the average because the average of 1 and 2 in your example is 2. Then with simple loop you can do something like this -
import math
l = [1, 2, 4, 8, 16, 32]
r = [l[0]]
for i in range(1,len(l)):
r.extend([math.ceil((l[i-1] l[i])/2), l[i]])
print(r)
After posting the answer, I saw that you are using round()