[BangPypers] partial flattening of list

Anand Balachandran Pillai abpillai at gmail.com
Tue Jul 27 11:46:03 CEST 2010


On Tue, Jul 27, 2010 at 2:29 PM, Shekhar Tiwatne <pythonic at gmail.com> wrote:

> On Tuesday 27 July 2010 12:18 PM, Vikram wrote:
>
>> have the following:
>>
>>
>>
>>> x
>>>>>
>>>>>
>>>> [['NM100', 1, 2], ['NM100', 3, 4], ['NM200', 5, 6]]
>>
>>
>>> for i in x:
>>>>>
>>>>>
>>>> ...   print i
>> ...
>> ['NM100', 1, 2]
>> ['NM100', 3, 4]
>> ['NM200', 5, 6]
>>
>> ------
>> how does one obtain list z such that
>>
>> z = [['NM100',1,2,3,4],['NM200',5,6]]
>>
>
This problem begs for the use of collections.defaultdict class.

All the other solutions are ok, but defaultdict is meant to solve
problems like this.

Here is the solution.

>>> import collections
>>> l=[['NM100', 1, 2], ['NM100', 3, 4], ['NM200', 5, 6]]
>>> l2=[[x[0], x[1:]] for x in l]
>>> d = collections.defaultdict(list)
>>> for k, v in l2: d[k].extend(v)
>>> [[k, v] for k,v in d.iteritems()]
[['NM100', [1, 2, 3, 4]], ['NM200', [5, 6]]]

What you want are the elements of the final list.

--Anand


More information about the BangPypers mailing list