On Tue, Jul 27, 2010 at 2:29 PM, Shekhar Tiwatne <[email protected]> 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 _______________________________________________ BangPypers mailing list [email protected] http://mail.python.org/mailman/listinfo/bangpypers
