[BangPypers] partial flattening of list

Vikram kpguy at rediffmail.com
Tue Jul 27 12:45:10 CEST 2010


Hi Anand,vijay, and others,
we have python 2.4.3 at our workplace and defaultdict is not present in the collections module in this python version.

>>> dir(collections)
['__doc__', '__file__', '__name__', 'deque']
>>> 

Also, could u suggest some way to tackle the following problem:
Given:

l = [['NM100', 1, 3], ['NM100', 7, 10], ['NM200', 13, 16]]

want something like:
 z = [['NM100',[1,2,3,7,8,9,10]],['NM200',[13,14,15,16]]]

On Tue, 27 Jul 2010 15:33:00 +0530  wrote
>On Tue, Jul 27, 2010 at 3:16 PM, Anand Balachandran Pillai <

abpillai at gmail.com> wrote:



>

>

> On Tue, Jul 27, 2010 at 2:29 PM, Shekhar Tiwatne 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.

>



I didn't notice you want



z = [['NM100',1,2,3,4],['NM200',5,6]]



rather than,



z= [['NM100', [1, 2, 3, 4]], ['NM200', [5, 6]]]



So replace last line with,



>>> [[k] + v for k,v in d.iteritems()]

[['NM100', 1, 2, 3, 4], ['NM200', 5, 6]]







> --Anand

>

>

>

>







-- 

--Anand

_______________________________________________

BangPypers mailing list

BangPypers at python.org

http://mail.python.org/mailman/listinfo/bangpypers



More information about the BangPypers mailing list