Just for clarification, you can do it also with a dictionary, but with a defaultdict you can append directly items to a list if it's not set.<br clear="all">---<br>Check my blog!<br><a href="http://wrongsideofmemphis.wordpress.com">http://wrongsideofmemphis.wordpress.com</a><br>
<br><br><div class="gmail_quote">On Tue, Jul 27, 2010 at 2:48 PM, Jaime Buelta <span dir="ltr"><<a href="mailto:jaime.buelta@gmail.com">jaime.buelta@gmail.com</a>></span> wrote:<br><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">
You can use a defaultdict to order the items and then convert that back again to a nested list:<div><div>>>> from collections import defaultdict</div><div>>>> d = defaultdict(list)</div><div>>>> for i in x:</div>
<div>... d[i[0]].extend(i[1:])</div><div>... </div><div>>>> d</div><div>defaultdict(<type 'list'>, {'NM100': [3, 4, 5, 6, 7, 10, 11, 12, 13], 'NM200': [15, 16, 17]})</div><div>>>> z = [ [k] + v for k,v in d.items() ]</div>
<div class="im">
<div>>>> z</div><div>[['NM100', 3, 4, 5, 6, 7, 10, 11, 12, 13], ['NM200', 15, 16, 17]]</div></div></div><div><br></div><div><br clear="all">---<br>Check my blog!<br><a href="http://wrongsideofmemphis.wordpress.com" target="_blank">http://wrongsideofmemphis.wordpress.com</a><br>
<br><br><div class="gmail_quote"><div><div></div><div class="h5">On Tue, Jul 27, 2010 at 2:32 PM, Vikram K <span dir="ltr"><<a href="mailto:kpguy1975@gmail.com" target="_blank">kpguy1975@gmail.com</a>></span> wrote:<br>
</div></div><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex"><div><div></div><div class="h5">
Suppose i have this nested list:<br><br>>>> x<br>[['NM100', 3, 4, 5, 6, 7], ['NM100', 10, 11, 12, 13], ['NM200', 15, 16, 17]]<br>>>> for i in x:<br>... print i<br>... <br>['NM100', 3, 4, 5, 6, 7]<br>
['NM100', 10, 11, 12, 13]<br>['NM200', 15, 16, 17]<br>>>> <br><br>how do i obtain from the above the following nested list:<br><br>>>> z<br>[['NM100', 3, 4, 5, 6, 7, 10, 11, 12, 13], ['NM200', 15, 16, 17]]<br>
>>> for i in z:<br>... print i<br>... <br>['NM100', 3, 4, 5, 6, 7, 10, 11, 12, 13]<br>['NM200', 15, 16, 17]<br>>>> <br>
<br></div></div>_______________________________________________<br>
python-uk mailing list<br>
<a href="mailto:python-uk@python.org" target="_blank">python-uk@python.org</a><br>
<a href="http://mail.python.org/mailman/listinfo/python-uk" target="_blank">http://mail.python.org/mailman/listinfo/python-uk</a><br>
<br></blockquote></div><br></div>
</blockquote></div><br>