toy list processing problem: collect similar terms

Paul Rubin no.email at nospam.invalid
Sun Sep 26 08:17:23 CEST 2010


Python solution follows (earlier one with an error cancelled).  All
crossposting removed since crossposting is a standard trolling tactic.

    from collections import defaultdict

    def collect(xss):
        d = defaultdict(list)
        for xs in xss:
            d[xs[0]].extend(xs[1:])
        return list(v for k,v in sorted(d.items()))

    y = [[0,'a','b'], [1,'c','d'], [2,'e','f'], [3,'g','h'], [1,'i','j'],
         [2,'k','l'], [4,'m','n'], [2,'o','p'], [4,'q','r'], [5,'s','t']]

    print collect(y)



More information about the Python-list mailing list