this is an exercise in python, I can not use pandas just built-in python functions.
I have this list:
['a', 1],
['b', 1],
['a', 2],
['a', 2],
The output, should look like:
['a', 5],
['b', 1],
This is the code I have so far, but I’m getting basically same list.
result = []
for x,y in list_data:
if x not in result:
result.append([x, int(y)])
else:
result[1] += int(y)
result
>Solution :
You can make a dictionary to compute the totals and then convert it back to a list:
data = [['c', 2], ['a', 1], ['b', 1], ['a', 2], ['a', 2], ['c', 3]]
totals = {} # could use collections.defaultdict for this part
for k, v in data:
totals[k] = totals.get(k, 0) + v
print(totals) # {'c': 5, 'a': 5, 'b': 1}
output = [[k, v] for k, v in totals.items()]
# or, output = list(map(list, totals.items()))
# or, output = list(totals.items()) # if you are fine with a list of tuples
print(output) # [['c', 5], ['a', 5], ['b', 1]]
# if you want the output to be sorted alphabetically
output = sorted(output, key=lambda lst: lst[0])
print(output) # [['a', 5], ['b', 1], ['c', 5]]