So here is what I am trying to achieve in Python:
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?
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.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments