user3641829 - 1 month ago 4x

Python Question

So here is what I am trying to achieve in Python:

- I have a list "A" with unsorted and repeated indices.
- I have a list "B" with some float values
- Length A = Length B
- I want list "C" with summed values of B based on the repeated indices in A in a sorted ascending manner.

Example:

`A=[0 , 1 , 0 , 3 , 2 , 1 , 2] (indicates unsorted and repeated indices)`

`B=[25 , 10 , 15 , 10 , 5 , 30 , 50] (values to be summed)`

`C=[25+15 , 10+30 , 5+50 , 15] (summed values in a sorted manner)`

So far I know how to do the sorting bit with:

`C= zip(*sorted(zip(A, B)))`

Getting the result:

`[(0, 0, 1, 1, 2, 2, 3), (15, 25, 10, 30, 5, 50, 10)]`

But I do not know how to do the sum.

What would be a good way to create list C?

Answer

Use `zip()`

in combination with a `dict`

:

```
A = [0 , 1 , 0 , 3 , 2 , 1 , 2]
B = [25 , 10 , 15 , 10 , 5 , 30 , 50]
sums = {}
for key, value in zip(A,B):
try:
sums[key] += value
except KeyError:
sums[key] = value
print(sums)
# {0: 40, 1: 40, 2: 55, 3: 10}
```

And see **a demo on ideone.com**.

Source (Stackoverflow)

Comments