toy list processing problem: collect similar terms

Arnaud Delobelle arnodel at gmail.com
Sun Sep 26 10:29:53 CEST 2010


On 26 Sep, 08:47, livibetter <livibet... at gmail.com> wrote:
> Here is mine for Python:
>
> l = [[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']]
> d = {}
> for idx, items in [(e[0], e[1:]) for e in l]: d[idx] = d[idx] + items
> if idx in d else items
> print d.values()
>
> Output:
> [['a', 'b'], ['c', 'd', 'i', 'j'], ['e', 'f', 'k', 'l', 'o', 'p'],
> ['g', 'h'], ['m', 'n', 'q', 'r'], ['s', 't']]

from itertools import groupby
from operator import itemgetter

l = [[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']]

[
    [x for g in gs for x in g[1:]]
    for _, gs in groupby(sorted(l), itemgetter(0))
]

--
Arnaud



More information about the Python-list mailing list