How to sum elements of a list corresponding to elements of another list in python
Question: I have two lists:

    
    
    a=[25,23,18,28]
    

and

    
    
    b=[1,2,2,3]
    

I want to sum the corresponding values in `a` to similar values in `b`, so it
would look like this:

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

Sorry for the confusion. Stealing JPeroutek's clarification: It looks to me
like he wants only unique values to exist in `return_b`. The values in `a`
correspond to those in `b`. Wherever you have a duplicate in `b`, you sum the
corresponding `a` values.

Nathan Bartley's answer worked for me.


Answer: A good way to do this would be to use a dictionary. The logic is very much
like JPeroutek describes. You go through list b, store the corresponding
number in list a, and if you encounter a value in b you've already seen, then
you add the new number in a it. You might try something like this to generate
it:

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

In case the try & except doesn't make sense you can rewrite those four lines
to look like this

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

This will result in a dictionary that looks like the following:

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

It's important to note that the dictionary may not preserve the order that you
want. For example:

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

would result in

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

If ordering is important, this would pose a problem with the next step.

* * *

You can split the dictionary into ret_a and ret_b by messing with the result
of

    
    
    res.items()
    

for instance:

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

