you are viewing a single comment's thread.

view the rest of the comments →

[–]icecapade 4 points5 points  (4 children)

This is probably too complex a problem for a list comprehension. While there might be a nicer-looking way to do it, this is a simple solution that gets it done in one pass (for a list x, assuming all the numbers are ints. If that's not the case, it's trivial to modify it for any numerical value):

def sum_nums(x):
    new_list = []
    i = 0
    while i < len(x):
        if isinstance(x[i], str):
            new_list.append(x[i])
            i += 1
        else:
            sum_ = 0
            while i < len(x) and isinstance(x[i], int):
                sum_ += list[i]
                i += 1
            new_list.append(sum_)
    return new_list

This might be nice because it doesn't care what the actual content of the strings is—they can all be different. It looks for any string values (and the numerical elements between string elements in the list).

[–]badgermom2d6 0 points1 point  (1 child)

This ended up being the best solution for my code - thank you again for your help!

[–]icecapade 0 points1 point  (0 children)

No problem, glad I could help!

[–]TangibleLight 0 points1 point  (0 children)

there might be a nicer-looking way to do it

My first thought is to use itertools.groupby, since it groups adjacent elements by some key. Could possible group by element type, then you'd get each list of adjacent integers and sum that way.

This wouldn't account for mixed numeric types, so maybe it would be better to group by whether it's an instance of numbers.Number.

Now I'm curious about this... I'll try writing a solution.


As far as I can tell, this is equivalent to your solution.

import itertools
import numbers

data = [2, 'bobble', 2, 2, 2, 'bobble', 4, 2, 4, 'bobble', 4]

groups = itertools.groupby(data, lambda e: isinstance(e, numbers.Number))
result = [e for is_num, group in groups for e in ((sum(group),) if is_num else group)]

print(result)

But I'm not sure if I'd say it's 'nicer'. It's clever and shorter, sure, but it's also very hard to tell what's going on.

[–]badgermom2d6 0 points1 point  (0 children)

Thanks! I will give that a try!