S
The code fails because c is the sum of your entire column (lista_b) since you do c = sum(lista_b)when it should be the sum of the values lista_b for which the element x in the same index lista_a fulfills if i == x.If we follow your original idea, the code should be like this:lista_a = ["A", "A","A", "A", "B", "B", "B", "B", "B", "C", "C", "D", "D", "D"]
lista_b = [23, 4, 345, 32, 534, 6, 323, 5, 323, 13, 17, 19, 23, 7]
lista_a2 = set(lista_a)
l = []
for i in lista_a2:
c = 0
for indice, x in enumerate(lista_a):
if i == x:
c += lista_b[indice]
l.append((i, c))
l.sort()
However, this is very inefficient because we once did it over lista_b for each value other lista_a. The key to making this simple and efficient is to use a dictionary and zip to parrot on both lists in a single cycle:lista_a = ["A", "A","A", "A", "B", "B", "B", "B", "B", "C", "C", "D", "D", "D"]
lista_b = [23, 4, 345, 32, 534, 6, 323, 5, 323, 13, 17, 19, 23, 7]
res = dict.fromkeys(lista_a, 0)
for a, b in zip(lista_a, lista_b):
res[a] += b
print(*(f"{key}, {value}" for key, value in res.items()), sep="\n")
or using collections.defaultdict:import collections
res = collections.defaultdict(int)
for a, b in zip(lista_a, lista_b):
res[a] += b
print(*(f"{key}, {value}" for key, value in res.items()), sep="\n")
We can certainly use too. itertools.groupbyBut it doesn't seem to me the most readable or simple in this case.from itertools import groupby
from operator import itemgetter
res = [(key, sum(g[1] for g in group))
for key, group in groupby(sorted(zip(lista_a, lista_b)), itemgetter(0))]
print(*(f"{a}, {b}" for a, b in res), sep="\n")
We must always remember that itertools.groupby you need the data to be properly sorted according to the grouping key previously. In this case they were already, so sorted(zip(lista_a, lista_b)) I might as well stay. zip(lista_a, lista_b) simply, but if you are not, you have to order or the result will be incorrect.The exit in any case is:A, 404B, 1191C, 30D, 49