0

Is there an easy way to sum all similar values in a list using list comprehensions?

i.e. input:

[1, 2, 1, 3, 3]

expected output:

[6, 2, 2] (sorted)

I tried using zip, but it only works for max 2 similar values:

[x + y for (x, y) in zip(l[:-1], l[1:]) if x == y]

3 Answers 3

7

You can use Counter.

from collections import Counter
[x*c for x,c in Counter([1, 2, 1, 3, 3]).items()]
Sign up to request clarification or add additional context in comments.

1 Comment

I like the way Counter :)
3
from itertools import groupby
a=[1, 2, 1,1,4,5,5,5,5, 3, 3]

print sorted([sum(g) for i,g in groupby(sorted(a))],reverse=True)

#output=[20, 6, 4, 3, 2]

explantion for the code

  1. first sort the list using sorted(a)

  2. perform groupby to make groupf of similar elements

  3. from each group use sum()

2 Comments

Shouldn't it be ; print sorted([sum(g) for i,g in groupby(sorted(a))],reverse=True) ? Otherwise, i see TypeError: 'list' object is not callable
@myildirim please check now. i have tested it. i am not getting any error
0

You can use collections.Counter for this, this will take O(N) time.:

>>> from collections import Counter
>>> lst = [1, 2, 1, 3, 3]
>>> [k*v for k, v in Counter(lst).iteritems()]
[2, 2, 6]

Here Counter() returns the count of each unique item, and then we multiply those numbers with their count to get the sum.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.