Sum Of Second Value In Nested List By First Value Using List Comprehension In Python
x = [(5, 65), (2, 12), (5, 18), (3, 35), (4, 49), (4, 10), (1, 27), (1, 1), (4, 71), (2, 41), (2, 17), (1, 25), (2, 62), (5, 65), (4, 5), (1, 51), (1, 13), (5, 92)
Solution 1:
Using pandas
:
>>>import pandas as pd>>>df = pd.DataFrame(x)>>>df.groupby(0).sum()[1].tolist()
[117, 194, 35, 135, 321]
Using itertools.groupby
:
>>>from itertools import groupby>>>keys, values = map(iter, zip(*sorted(x)))>>>[sum(g) for _, g in groupby(values, lambda _: next(keys))]
[117, 194, 35, 135, 321]
Solution 2:
Use a dictionary:
d = dict()
for i, val in x:
d.setdefault(i , 0)
d[i] += val
result = list(d.items())
Solution 3:
A simple solution using just list comprehension:
x = [(5, 65),
(2, 12),
(5, 18),
(3, 35),
(4, 49),
(4, 10),
(1, 27),
(1, 1),
(4, 71),
(2, 41),
(2, 17),
(1, 25),
(2, 62),
(5, 65),
(4, 5),
(1, 51),
(1, 13),
(5, 92),
(2, 62),
(5, 81)]
key_range = set([k for k, _ in x])
res = [sum([v for k, v in x if k == i]) for i in key_range]
Solution 4:
If you need them sorted, then use itertools.groupby:
from itertools import groupby
from operator import itemgetter
x = [(5, 65), (2, 12), (5, 18), (3, 35), (4, 49), (4, 10), (1, 27), (1, 1), (4, 71), (2, 41),
(2, 17), (1, 25), (2, 62), (5, 65), (4, 5), (1, 51), (1, 13), (5, 92), (2, 62), (5, 81)]
result = [sum(v for _, v in value) for key, value in groupby(sorted(x), key=itemgetter(0))]
print(result)
Output
[117, 194, 35, 135, 321]
But the above approach is not very efficient, so I suggest you could use a defaultdict:
from collections importdefaultdictx= [(5, 65), (2, 12), (5, 18), (3, 35), (4, 49), (4, 10), (1, 27), (1, 1), (4, 71), (2, 41),
(2, 17), (1, 25), (2, 62), (5, 65), (4, 5), (1, 51), (1, 13), (5, 92), (2, 62), (5, 81)]
counts = defaultdict(int)
for key, value in x:
counts[key] += valueresult= [v for _, v in sorted(counts.items())]
print(result)
Output
[117, 194, 35, 135, 321]
As a rule of thumb when you are dealing with values that need to reduce or accumulated by a key using a list comprehension may not be the most efficient approach.
Note
The most efficient approach that fits your example and only your example (small numbers of keys in a small range [1, 5]) is to simply do:
result= [0for _ inrange(5)]
for key, valuein x:
result[key -1] +=value
print(result)
Solution 5:
Not very efficient, but if you want it in a list comprehension, you can do it like this:
[ sum(n for k,n in x if k==K) for K in range(1,6) ][117, 194, 35, 135, 321]
A for-loop on the list of tuples to "pigeonhole" the additions in a list of sums would be more efficient:
sums = [0]*5for k,n in x: sums[k-1] += n
[117, 194, 35, 135, 321]
Post a Comment for "Sum Of Second Value In Nested List By First Value Using List Comprehension In Python"