[python-uk] nested list help

Jaime Buelta jaime.buelta at gmail.com
Tue Jul 27 15:48:53 CEST 2010


You can use a defaultdict to order the items and then convert that back
again to a nested list:
>>> from collections import defaultdict
>>> d = defaultdict(list)
>>> for i in x:
...   d[i[0]].extend(i[1:])
...
>>> d
defaultdict(<type 'list'>, {'NM100': [3, 4, 5, 6, 7, 10, 11, 12, 13],
'NM200': [15, 16, 17]})
>>> z = [ [k] + v for k,v in d.items() ]
>>> z
[['NM100', 3, 4, 5, 6, 7, 10, 11, 12, 13], ['NM200', 15, 16, 17]]


---
Check my blog!
http://wrongsideofmemphis.wordpress.com


On Tue, Jul 27, 2010 at 2:32 PM, Vikram K <kpguy1975 at gmail.com> wrote:

> Suppose i have this nested list:
>
> >>> x
> [['NM100', 3, 4, 5, 6, 7], ['NM100', 10, 11, 12, 13], ['NM200', 15, 16,
> 17]]
> >>> for i in x:
> ...   print i
> ...
> ['NM100', 3, 4, 5, 6, 7]
> ['NM100', 10, 11, 12, 13]
> ['NM200', 15, 16, 17]
> >>>
>
> how do i obtain from the above the following nested list:
>
> >>> z
> [['NM100', 3, 4, 5, 6, 7, 10, 11, 12, 13], ['NM200', 15, 16, 17]]
> >>> for i in z:
> ...   print i
> ...
> ['NM100', 3, 4, 5, 6, 7, 10, 11, 12, 13]
> ['NM200', 15, 16, 17]
> >>>
>
> _______________________________________________
> python-uk mailing list
> python-uk at python.org
> http://mail.python.org/mailman/listinfo/python-uk
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-uk/attachments/20100727/c05697ba/attachment.html>


More information about the python-uk mailing list