Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Assign Value to a list in python and sum the values

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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]]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading