[Solved] Python 3.6: when a value in a list changes, find the sum of the values in another list?


Now that I understand that the list A itself is not going to change, but you expressed the idea of change meaning that the list has partitions where there are adjacent elements that are different, then a different solution comes to mind:

Given your original data:

A = ['1','1','1','3','3','4']

B = ['5','9','3','4','8','1']

We can use a defaultdict to group this data:

from collections import defaultdict
D = defaultdict(list)

for a, b in zip(A,B):
    D[a].append(int(b))

Just to show what we have collected:

for a, b in D.items():
    print(a,b)
>> 1 [5, 9, 3]
>> 3 [4, 8]
>> 4 [1]

Now we can compute some sums:

result = [sum(b) for a,b in D.items()]
print(result)
>> [17, 12, 1]

Notes about defaultdict:

When the instance is created:

D = defaultdict(list)

This creates a defaultdict which, when it encounters new keys will create an instance of the parameter. In this case it creates a new list

So each line:

D[a].append(int(b))

When a is a key that D has not seen before, a new list is created, which is returned, to which the .append(.... is applied.

2

solved Python 3.6: when a value in a list changes, find the sum of the values in another list?