I have a list of str and int elements as given below
L = [1, "a", "b", 1, 2, 1, "d", 1, "e", 4, 5, "f", "g", 2]
I want to sum up numbers found between two string elements so resultant output is excpected like this.
[1, "a", "b", 4, "d", 1, "e", 9, "f", "g", 2]
I would like to solve this in a pythonic way. How this can be done?
>Solution :
Looks like a good use case for itertools.groupby. We group the successive values by type (int/float or other), then we sum the numbers and add the others as is:
from itertools import groupby, chain
L = [1, "a", "b", 1, 2, 1, "d", 1, "e", 4, 5, "f", "g", 2]
out = list(chain.from_iterable(([sum(g)] if k else g for k, g in
groupby(L, key=lambda x: isinstance(x, (int, float))))))
Output:
[1, 'a', 'b', 4, 'd', 1, 'e', 9, 'f', 'g', 2]
Same approach combined with a loop:
out = []
for k, g in groupby(L, key=lambda x: isinstance(x, (int, float))):
if k:
out.append(sum(g))
else:
out.extend(g)
And a more classical approach using only a loop:
out = []
add = False
for item in L:
if isinstance(item, int):
if add:
out[-1] += item
else:
add = True
out.append(item)
else:
add = False
out.append(item)