I have a list of tuples, each with a string and a integer value:
list_a= [('0', 60), ('0', 5), ('2', 1), ('3', 14), ('4', 39), ('1', 17), ('2', 14), ('2', 29), ('4', 1), ('3', 1), ('3', 16), ('4', 8)]
I would like to add the values if the strings are the same AND only if the strings are adjacent to each other, making the output look like:
result=[('0', 65), ('2', 1), ('3', 14), ('4', 39), ('1', 17), ('2', 43), ('4', 1), ('3', 17), ('4', 8)]
Not using any imported packages
Thanks a lot !
CodePudding user response:
You can try the following; accumulate the values until there is a change in the "key":
list_a = [('0', 60), ('0', 5), ('2', 1), ('3', 14), ('4', 39), ('1', 17), ('2', 14), ('2', 29), ('4', 1), ('3', 1), ('3', 16), ('4', 8)]
output = []
v_accu = 0 # value accumulator
k_prev = None
for k, v in list_a:
if k_prev is not None and k != k_prev: # can omit "is not None"
output.append((k_prev, v_accu)) # insert the accumulated value so far
v_accu = v # reset the accumulator
else:
v_accu = v # keep adding
k_prev = k # update k_prev
output.append((k_prev, v_accu)) # final insertion
print(output)
# [('0', 65), ('2', 1), ('3', 14), ('4', 39), ('1', 17), ('2', 43), ('4', 1), ('3', 17), ('4', 8)]
But with some standard modules, you can do it in a simpler way:
from itertools import groupby
from operator import itemgetter
list_a = [('0', 60), ('0', 5), ('2', 1), ('3', 14), ('4', 39), ('1', 17), ('2', 14), ('2', 29), ('4', 1), ('3', 1), ('3', 16), ('4', 8)]
output = [(k, sum(map(itemgetter(1), g))) for k, g in groupby(list_a, key=itemgetter(0))]
print(output)