How to sum elements of a list corresponding to elements of another list in python -


i have 2 lists:

a=[25,23,18,28] 

and

b=[1,2,2,3] 

i want sum corresponding values in a similar values in b, this:

return_a=(25,41,28) return_b=(1,2,3) 

sorry confusion. stealing jperoutek's clarification: looks me wants unique values exist in return_b. values in a correspond in b. wherever have duplicate in b, sum corresponding a values.

nathan bartley's answer worked me.

a way use dictionary. logic jperoutek describes. go through list b, store corresponding number in list a, , if encounter value in b you've seen, add new number in it. might try generate it:

res = {} ix in xrange(len(b)):     cur_b = b[ix] # grab next number in b     cur_a = a[ix] # grab corresponding number in     try: # if we've seen cur_b before can add cur_a         res[cur_b] += cur_a      except keyerror: # otherwise we've never seen cur_b before set cur_a         res[cur_b] = cur_a 

in case try & except doesn't make sense can rewrite 4 lines this

if cur_b in res:  # asks if cur_b in set of keys of res     res[cur_b] += cur_a else:     res[cur_b] = cur_a 

this result in dictionary looks following:

{(1, 25), (2, 41), (3, 28)} 

it's important note dictionary may not preserve order want. example:

b = [3, 3, 2, 1] = [12, 4, 6, 6] 

would result in

{(1, 6), (2, 6), (3, 15)} 

if ordering important, pose problem next step.


you can split dictionary ret_a , ret_b messing result of

res.items() 

for instance:

ret_a = [t[1] t in res.items()] ret_b = [t[0] t in res.items()] 

Comments