Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to insert average values of list into the same list?

Given this list:

[1, 2, 4, 8, 16, 32]

I want to end up with this list:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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:]))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading