Vikram K 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]
 >>>



z = [['NM100', 3, 4, 5, 6, 7], ['NM100', 10, 11, 12, 13], ['NM200', 15, 16, 17]]

from itertools import groupby

# assumes that the data is already sorted by the first element as it is here
# if not then you must sort, eg. with the same function you group by:
# z.sort(key=lambda X: X[0])
# also assumes that there are no empty lists

def merge(inlist):
    for k, g in groupby(inlist, lambda X: X[0]):
        k = [k]
        for item in g:
            k.extend(item[1:])
        yield k

print list(merge(z))

[['NM100', 3, 4, 5, 6, 7, 10, 11, 12, 13], ['NM200', 15, 16, 17]]

def merge(inlist):
    for k, g in groupby(inlist, lambda X: X[0]):
        newlist = []
        for item in g:
            newlist.extend(item[1:])
        yield k, newlist

print dict(merge(z))

{'NM100': [3, 4, 5, 6, 7, 10, 11, 12, 13], 'NM200': [15, 16, 17]}

_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

Reply via email to