I have
a bunch of lists of integers from 0 to somewhere around 1000, here are the first elements of such a list:
oldlist = [216, 216, 199, 253, 271, 217, 183, 225, 199, 217, 217, 235, 254, 217, 235, 235, 234, 234, 235, 231, 183, 263, 298, 190, 248, 200, 223, 199, 225, 195, 240]
I want
to add consecutive list elements that are >215 and merge them into a single list element, leaving the rest of the list as it is. For the above list it should result in:
newlist = [432, 199, 741, 183, 225, 199, 2544, 183, 561, 190, 248, 200, 223, 199, 225, 195, 240]
I tried
def dtadder(oldlist):
newlist = []
nlidx = 0 # newlist index
for idx, x in enumerate(oldlist):
if idx > 0 and oldlist[idx - 1] > 215 and oldlist[idx] > 215:
x = oldlist[idx] + newlist[nlidx - 1]
newlist.remove(newlist[nlidx - 1])
nlidx -= 1
newlist.append(x)
nlidx += 1
return newlist
What happened
is that everything works out exactly how I expect it to, until the 116th iteration of the loop (nlidx=85), when for some reason newlist[4]= 225 is removed from the list. This keeps occasionally happening with other elements though I haven't figured out when and why. It seems that only elements >215 are removed.
What am I missing here? I'm fairly new to programming and python but I feel there should be an easier and more readable way to do this. Apart from a solution to my problem I would be really interested in understanding why my solution doesn't work.