[python-uk] nested list help

Jaime Buelta jaime.buelta at gmail.com
Tue Jul 27 15:49:40 CEST 2010


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.
---
Check my blog!
http://wrongsideofmemphis.wordpress.com


On Tue, Jul 27, 2010 at 2:48 PM, Jaime Buelta <jaime.buelta at gmail.com>wrote:

> 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/ee2f93e0/attachment.html>


More information about the python-uk mailing list