Python: three levels of nesting with list comprehension
<p>I am trying to achieve a nesting of three levels because I need to group some data.</p>

<p>I have a list of matches, and each of these matches belong to particular rounds. I want to regroup these matches into separate nested lists for each round, except I don't want to store the whole match in these lists, but only the scores.</p>

<p>To clarify, we have this:</p>

<pre><code>all_matches = [final_match, semifinal1_match, semifinal2_match]
</code></pre>

<p>These matches have properties like <code>round</code>, <code>home_score</code> and <code>away_score</code>. What I am trying to do is group them in the following fashion:</p>

<pre><code>[
    [[1, 3], [2, 0]],  # semifinal 
    [[1, 0]]           # final round
]
</code></pre>

<p>I managed to group matches into nested lists by the round they belong to:</p>

<pre><code>[list(matches) for round, matches in groupby(all_matches, key=attrgetter('round'))]
</code></pre>

<p>And this is the result:</p>

<pre><code>[[semifinal1_match, semifinal2_match], [final_match]]
</code></pre>

<p>This is not quite what I am after. I am having trouble trying to figure out how the list comprehension syntax would be to extract only the scores (in a list) for each match into its respective round list, instead of having the whole match in there.</p>

<p>You can expand each match getting the required attributes from your current result using a nested <em>list comprehension</em>:   </p>

<pre><code>[[[m.home_score, m.away_score] for m in matches]
                               for _, matches in groupby(all_matches, key=attrgetter('round'))]
</code></pre>

python python-2.7