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>Use <code>zip()</code> in combination with a <code>dict</code>:</p>

<pre><code>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}
</code></pre>

<p>And see <a href="http://ideone.com/OxbT5s" rel="nofollow"><strong>a demo on ideone.com</strong></a>.</p>

python list