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>It is actually a bit unclear what you want, but if you want them to be <em>indexed</em> by whatever the number is, you shouldn't even use a list, but a Counter instead:</p>

<pre><code>&gt;&gt;&gt; from collections import Counter
&gt;&gt;&gt; c = Counter()
&gt;&gt;&gt; A = [0, 1, 0, 3, 2, 1, 2]
&gt;&gt;&gt; B = [25, 10, 15, 10 , 5, 30, 50]
&gt;&gt;&gt; for k, v in zip(A, B):
...     c[k] += v
...
&gt;&gt;&gt; c
Counter({2: 55, 0: 40, 1: 40, 3: 10})
&gt;&gt;&gt; c[0]
40
</code></pre>

<p>If you really want a list, you can use</p>

<pre><code>&gt;&gt;&gt; [i[1] for i in sorted(c.items())]
</code></pre>

<p>but then any missing key would cause the rest of the values show up upper, which might or might not be that what you wanted.</p>

python list