PYTHON: Summing up elements from one list based on indices in another list
<p>So here is what I am trying to achieve in Python:</p>

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

<p>Example:</p>

<p><code>A=[0 , 1 , 0 , 3 , 2 , 1 , 2] (indicates unsorted and repeated indices)</code></p>

<p><code>B=[25 , 10 , 15 , 10 , 5 , 30 , 50] (values to be summed)</code></p>

<p><code>C=[25+15 , 10+30 , 5+50 , 15] (summed values in a sorted manner)</code></p>

<p>So far I know how to do the sorting bit with:</p>

<p><code>C= zip(*sorted(zip(A, B)))</code></p>

<p>Getting the result:</p>

<p><code>[(0, 0, 1, 1, 2, 2, 3), (15, 25, 10, 30, 5, 50, 10)]</code></p>

<p>But I do not know how to do the sum.</p>

<p>What would be a good way to create list C?</p>

<p>You could use <a href="https://docs.python.org/3/library/itertools.html#itertools.groupby" rel="nofollow">groupby</a>, if the order matters:</p>

<pre><code>In [1]: A=[0 , 1 , 0 , 3 , 2 , 1 , 2]

In [2]: B=[25 , 10 , 15 , 10 , 5 , 30 , 50]

In [3]: from itertools import groupby

In [4]: from operator import itemgetter

In [5]: C = [sum(map(itemgetter(1), group))
   ...:      for key, group in groupby(sorted(zip(A, B)),
   ...:                                key=itemgetter(0))]

In [6]: C
Out[6]: [40, 40, 55, 10]
</code></pre>

<p>or <a href="https://docs.python.org/3/library/collections.html#collections.defaultdict" rel="nofollow"><code>defaultdict(float)</code></a>, if it does not:</p>

<pre><code>In [10]: from collections import defaultdict

In [11]: res = defaultdict(float)

In [12]: for k, v in zip(A, B):
    ...:     res[k] += v
    ...:     

In [13]: res
Out[13]: defaultdict(float, {0: 40.0, 1: 40.0, 2: 55.0, 3: 10.0})
</code></pre>

<p>Note that <code>dict</code>s in python are unordered (you are not to trust any CPython implementation details).</p>

python list