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

How to sum values in list?

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??

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

>Solution :

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']
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