Python sum array of objects into objects
<p>I have a list (name=carpet) of objects type mini_carpet.
Mini_carpet contains a list of objects called packages.
Packages has various properties, the one interesting to me is nr_buys.</p>

<p>What I want to do is to sum the various nr_buys that are within a mini_carpet, within a carpet.
This is what I have done so far:</p>

<pre><code>for d in range(0, carpet.__len__() - 1, +1):
nr_total = sum(carpet[d].packages[i].nr_buys for i in carpet[d].packages)
</code></pre>

<p>This is giving me an error because list indices must be integers.
Any help?</p>

<p>Thanks! </p>

<blockquote>
  <p>sum the <em>various</em> <code>nr_buys</code> that are within a mini_carpet, within a carpet</p>
</blockquote>

<p>Asides what others have said about trying to index your list with a non integer object, you're also throwing away the result of previous iterations. </p>

<p>You can use a mapping/dictionary to keep these results using the carpet index as the key, which can later be used to access the result of the sums of <code>nr_buys</code> values of the packages in that carpet:</p>

<pre><code>nr_total = {}

for i, c in enumerate(carpet):
    nr_total[i] = sum(package.nr_buys for package in c.packages)
</code></pre>

<p>To get the total <code>nr_buys</code> for all the carpets, you'll simply do:</p>

<pre><code>total = sum(nr_total.values())
</code></pre>

python