I have a mixed list with strings and ints and I need to get to the sum of the numbers between each strings. Ideally the end result would be a list of tuples since each string and following numbers belong together (so order is important).
I can extract the number with iteration using isinstance
but the actual list is very large and I sometimes I have 1 or 2 numbers for each string.
my_list = ['a', 2, 1, 'b', 3, 'h', 50, 4, 'd', 4, 'v', 20, 7]
ideal_output = [('a', 3) ('b', 3), ('h', 54), ('d', 4), (v, 27)]
Here's a solution using itertools.groupby:
Output:
It does assume that there will be at least one number between the strings. If not you can check on the
len
ofg
and if that's more than 1, add a 0 for the value of the first value ing