Mejdi Dallel
Mejdi Dallel

Reputation: 632

Python sum list elements according to other list

I have this two lists :

x = [1, 2, 3, 1, 1, 2, 3]
y = [1.3, 0.5, 0.7, 1.9, 2.5, 3.1, 1.4]

I want to sum y elements according to every duplicate element in x.

For example, for the first element of x (=1), I will have to sum all y elements at indexs 0, 3 and 4 which are indexs of 1 in x. I want to save the element and its sum.

My output will be like this :

sum = [[1, 5.7],
       [2, 3.6],
       [3, 2.1]]

How can I code this ?

Upvotes: 1

Views: 56

Answers (3)

CDJB
CDJB

Reputation: 14486

Here's a solution using a one-liner:

>>> [[x_num, sum([y_num for i, y_num in enumerate(y) if x[i] == x_num])] for x_num in set(x)]
[[1, 5.7], [2, 3.6], [3, 2.0999999999999996]]

Upvotes: 2

yatu
yatu

Reputation: 88226

Here's one approach using a defaultdict:

from collections import defaultdict

d = defaultdict(float)
for k,v in zip(x,y):
    d[k] += v

list(map(list, d.items()))
# [[1, 5.7], [2, 3.6], [3, 2.0999999999999996]]

Upvotes: 4

Ajax1234
Ajax1234

Reputation: 71451

You can use itertools.groupby:

from itertools import groupby
x = [1, 2, 3, 1, 1, 2, 3]
y = [1.3, 0.5, 0.7, 1.9, 2.5, 3.1, 1.4]
d = [(a, list(b)) for a, b in groupby(sorted(enumerate(x), key=lambda x:x[1]), key=lambda x:x[1])]
result = [[a, sum(y[k] for k, _ in b)] for a, b in d]

Output:

[[1, 5.7], [2, 3.6], [3, 2.0999999999999996]]

Upvotes: 3

Related Questions