Group list of tuples by item
<p>I have this list as example:</p>

<pre><code>[(148, Decimal('3.0')), (325, Decimal('3.0')), (148, Decimal('2.0')), (183, Decimal('1.0')), (308, Decimal('1.0')), (530, Decimal('1.0')), (594, Decimal('1.0')), (686, Decimal('1.0')), (756, Decimal('1.0')), (806, Decimal('1.0'))]
</code></pre>

<p>Now i want to group by the id, so I will use <code>itemgetter(0)</code>:</p>

<pre><code>import operator, itertools
from decimal import *
test=[(148, Decimal('3.0')), (325, Decimal('3.0')), (148, Decimal('2.0')), (183, Decimal('1.0')), (308, Decimal('1.0')), (530, Decimal('1.0')), (594, Decimal('1.0')), (686, Decimal('1.0')), (756, Decimal('1.0')), (806, Decimal('1.0'))]

for _k, data in itertools.groupby(test, operator.itemgetter(0)):
    print list(data) 
</code></pre>

<p>I don't know why but I am getting this wrong output:</p>

<pre><code>[(148, Decimal('3.0'))]
[(325, Decimal('3.0'))]
[(148, Decimal('2.0'))]
[(183, Decimal('1.0'))]
[(308, Decimal('1.0'))]
[(530, Decimal('1.0'))]
[(594, Decimal('1.0'))]
[(686, Decimal('1.0'))]
[(756, Decimal('1.0'))]
[(806, Decimal('1.0'))]
</code></pre>

<p>As you can see the output is not grouped by id. However the code above works fine if I use <code>itemgetter(1)</code>. The output is grouped by decimal val.</p>

<pre><code>[(148, Decimal('3.0')), (325, Decimal('3.0'))]
[(148, Decimal('2.0'))]
[(183, Decimal('1.0')), (308, Decimal('1.0')), (530, Decimal('1.0')), (594, Decimal('1.0')), (686, Decimal('1.0')), (756, Decimal('1.0')), (806, Decimal('1.0'))]
</code></pre>

<p>What I am missing here?</p>

<p><code>itertools.groupby()</code> requires the data to be consistent or sorted.</p>

<p><code>[(148, Decimal('3.0')), (148, Decimal('2.0')), (325, Decimal('3.0'))]</code> will work but <code>[(148, Decimal('3.0')), (325, Decimal('3.0')), (148, Decimal('2.0'))]</code> will not as the id is <code>148, 325, 148</code> instead of <code>148, 148, 325</code>.</p>

python python-2.7 itertools