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>

<p>Another method of doing this, which I feel is more Pythonic, is:</p>

<pre><code>nr_total = sum(package.nr_buys for package in carpet[d].packages)
</code></pre>

<p>The difference, as stated above, is that calling <code>for x in list</code> in python gives you the items of the list, and not their indices. That means that the <code>i</code> in your answer is not the integer index in <code>packages</code> of your item, but your item from <code>packages</code> itself, which you can use directly.</p>

<p>Now this can be done from the start:</p>

<pre><code>nr_total = sum(package.nr_buys for mini_carpet in carpet for package in mini_carpet)
</code></pre>

<p>(don't ask me why Python uses that order, it confuses me as well, but that's how list comprehensions work.)</p>

python