How to sum values in list?

Question:

list = ['1297546327:0', '1297546327:1', '1297546327:1', '1297546327:0', '1297546327:0', '1297546327:0', '1297546327:0', '1297546327:1', '1297546327:1', '1297546327:1', '5138875960:0', '5138875960:1', '5138875960:0', '5138875960:0', '5138875960:1']

I have a list like this and I need to add values after ":" To get it like this

total = ['1297546327:5','5138875960:2']

How can you do that??

Answers:

Use itertools.groupby, for example:

alist = ['1297546327:0', '1297546327:1', '1297546327:1', '1297546327:0', '1297546327:0', '1297546327:0', '1297546327:0', '1297546327:1', '1297546327:1', '1297546327:1', '5138875960:0', '5138875960:1', '5138875960:0', '5138875960:0', '5138875960:1']


alist = [obj.split(':') for obj in alist]

result = {}
for k, g in groupby(sorted(alist), key=lambda x: x[0]):
    result[k] = sum(int(v) for _, v in g)

print(result)
# if you want num in ascending order (for desending order pass reverse=True to the sorted function):
# result = dict(sorted(result.items(), key=lambda obj: obj[1])) 

print([f'{k}:{v}' for k, v in  result.items()])

Output:

{'1297546327': 5, '5138875960': 2}
['1297546327:5', '5138875960:2']
Answered By: funnydman

It seems like maybe you should be using a dict instead of a list. That way you can assign each value before the : a value after the : and then add together all the values in the dict. Or maybe you should make two lists or use a pandas dataframe, but it seems like you are using the wrong type of datastructure for what you are trying to do

Answered By: Sven Asmussen

Here is a solution without using any external module:

pairs = [
    '1297546327:0',
    '1297546327:1',
    '1297546327:1',
    '1297546327:0',
    '1297546327:0',
    '1297546327:0',
    '1297546327:0',
    '1297546327:1',
    '1297546327:1',
    '1297546327:1',
    '5138875960:0',
    '5138875960:1',
    '5138875960:0',
    '5138875960:0',
    '5138875960:1'
]

d = {}

for k, v in (pair.split(':') for pair in pairs):
    d[k] = d[k] + int(v) if d.get(k) else int(v)

pairs_total = [f'{k}:{v}' for k, v in d.items()]

print(pairs_total)

The code above will output the following:

['1297546327:5', '5138875960:2']
Answered By: accdias
dic = {}
for i in lis:
    a = i.split(':')
    if dic.get(a[0]):
        dic[a[0]]=int(dic[a[0]])+int(a[1])
    else:
        dic[a[0]]=int(a[1])

total = [f'{k}:{v}' for k,v in dic.items()]
Answered By: Haseeb Ayoub

Here’s a solution using collections.defaultdict:

from collections import defaultdict

list_ = ['1297546327:0', 
     '1297546327:1', 
     '1297546327:1', 
     '1297546327:0', 
     '1297546327:0', 
     '1297546327:0', 
     '1297546327:0', 
     '1297546327:1', 
     '1297546327:1', 
     '1297546327:1', 
     '5138875960:0', 
     '5138875960:1', 
     '5138875960:0', 
     '5138875960:0', 
     '5138875960:1', 
     ]

tally = defaultdict(int)

for item in list_:
    key, value = item.split(':')
    tally[key] += int(value)

total = [f'{key}:{value}' for key, value in tally.items()]

print(total)

Output:

['1297546327:5', '5138875960:2']

Also note that it is bad practice to name variables the same as built-in functions and types, and other keywords like if, while, etc. Instead of list, name it list_, or simply use another name.

Answered By: GordonAitchJay
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.