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

summing up elements between two strings in list

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?

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

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