Вот решение, использующее itertools.groupby :
my_list = ['a', 2, 1, 'b', 3, 'h', 50, 4, 'd', 4, 'v', 20, 7]
from itertools import groupby
groups = groupby(my_list, key=type) # group-by the type of the value
result = []
for key, group in groups:
string = next(group) # get the string first, we'll skip over it otherwise
if key is str:
_, values = next(groups) # move the generator forward to get to the numbers
result.append((string, sum(values))) # sum up the numbers
print(result)
Выход:
[('a', 3), ('b', 3), ('h', 54), ('d', 4), ('v', 27)]
Предполагается, что между строками будет хотя бы одно число. Если нет, вы можете проверить len
из g
и, если это больше 1, добавить 0 для значения первого значения в g