[BangPypers] partial flattening of list
Shekhar Tiwatne
pythonic at gmail.com
Tue Jul 27 10:59:22 CEST 2010
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]]
> _______________________________________________
> BangPypers mailing list
> BangPypers at python.org
> http://mail.python.org/mailman/listinfo/bangpypers
>
A less readable solution using itertools
#------------
from itertools import *
get_first = lambda x: x[0]
filter_first_and_chain_rest = lambda seq: chain(*(x[1:] for x in seq))
data = [['NM100', 1, 2], ['NM100', 3, 4], ['NM200', 5, 6]]
grouped = groupby(sorted(data), get_first)
print list ([label] + list(filter_first_and_chain_rest(grp)) for label,
grp in grouped)
~Shekhar
More information about the BangPypers
mailing list