Reputation: 27
Hello I would like to know how to use a for loop to go through a list and insert an element after each other element in a new list.
I have looked at this link Insert element in Python list after every nth element
but when I tried that method it was giving me the exact same problem when implementing it in my code
"""
Created on Sat Mar 28 20:40:37 2020
@author: DeAngelo
"""
import math
import matplotlib.pyplot as plt
import numpy as np
from numpy import sqrt
from quadpy import quad
import scipy.integrate as integrate
import scipy.special as special
experiment = [1,2,3,4,5]
count = len(experiment)
after = []
new = []
for i in range(0,count-1):
average2 = (experiment[i] + experiment[i+1])/2
new.append(average2)
print(experiment)
for i in range(0,count-1):
just = experiment.insert(i+1,new[i])
print(new,'\n')
print(experiment)
1st print(experiment) -> [1, 2, 3, 4, 5]
print(new,'\n') -> [1.5, 2.5, 3.5, 4.5]
and
2nd, print(experiment) -> [1, 1.5, 2.5, 3.5, 4.5, 2, 3, 4, 5]
But I want it to be [1,1.5,2,2.5,3,3.5,4,4.5,5] I know I can use merge and sort, but I don't want to because I am working with a MUCH MUCH bigger list and it can't be sorted. This is just my baby list for right now.
I am really close I can feel it, it's like a sixth sense... Any help and guidance is much appreciated. Thanks a lot cutie
Upvotes: 0
Views: 3563
Reputation: 96
you can use this one-liner list comprehension
from itertools import zip_longest
a = [1,2,3,4,5]
b = [1.5, 2.5, 3.5, 4.5]
flat_list = [val for sublist in zip_longest(a,b) for val in sublist if val]
output = [1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5]
Upvotes: 0
Reputation: 9002
As an attempt to generate the required output list in a single pass using list comprehension I offer this:
e = [1, 2, 3, 4]
r = [e[i] if j == 0 else sum(e[i:i+2])/2. for i in range(len(e)) for j in range(min(len(e) - i, 2))]
assert r == [1, 1.5, 2, 2.5, 3, 3.5, 4]
I use a nested for loop just to switch between passing the original element to output and calculating average of subsequent elements.
Upvotes: 1
Reputation: 36755
For me it looks like task for roundrobin
from itertools recipes that is:
from itertools import cycle, islice
def roundrobin(*iterables):
"roundrobin('ABC', 'D', 'EF') --> A D E B F C"
# Recipe credited to George Sakkis
pending = len(iterables)
nexts = cycle(iter(it).__next__ for it in iterables)
while pending:
try:
for next in nexts:
yield next()
except StopIteration:
pending -= 1
nexts = cycle(islice(nexts, pending))
a = [1, 2, 3, 4, 5]
b = [10, 20, 30, 40]
ab = list(roundrobin(a,b))
print(ab)
Output:
[1, 10, 2, 20, 3, 30, 4, 40, 5]
Note that roundrobin
might be used for interleaving more than 2 iterables and always terminates on longest one. As you are working with a MUCH MUCH bigger list it has additional benefit of creating generator
rather than list
.
Upvotes: 0
Reputation: 1501
experiment = [1, 2, 3, 4, 5]
count = len(experiment)
for i in range(count - 1):
experiment.insert(2*i+1, (experiment[2*i] + experiment[2*i+1])/2)
print(experiment)
Upvotes: 1
Reputation: 3534
Inserting into the middle of a list a bunch of times is going to be very slow for a large dataset. It seems like you can just build a new list like you're doing:
first = [1, 2, 3, 4, 5]
second = []
for i in range(0, len(first) - 1):
avg = (first[i] + first[i+1]) / 2
second.append(first[i])
second.append(avg)
second.append(first[-1])
print(second)
Which prints:
[1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5]
Upvotes: 2