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>In Python, it's generally better to loop directly over the items in a list, rather than looping indirectly using indices. It's easier to read, and more efficient not to muck around with indices that you don't really need.</p>

<p>To get a total for each <code>mini_carpet</code> you can do this:</p>

<pre><code>for mini in carpet:
    nr_total = sum(package.nr_buys for package in mini)
    # Do something with nr_total
</code></pre>

<p>To get a single grand total, do a double <code>for</code> loop in the generator expression:</p>

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

python