newbie/ merging lists of lists with items in common

Neil Cerutti horpner at yahoo.com
Fri Feb 2 09:41:13 EST 2007


On 2007-02-02, ardief <rachele.defelice at gmail.com> wrote:
> Hi everyone
> Here is my problem:
> I have a list that looks like this -
> [['a', '13'], ['a', '3'], ['b', '6'], ['c', '12'], ['c', '15'], ['c',
> '4'], ['d', '2'], ['e', '11'], ['e', '5'], ['e', '16'], ['e', '7']]
>
> and I would like to end up with something like this, i.e. with
> the only one list per letter:
>
> [['a', ['13' '3']], ['b', '6'], ['c', ['12', '15', '4']], ['d', '2'],
> ['e', ['11', '5', '16', '7']]]
>
> I have the feeling it's trivial, and I've scoured the group
> archives - sets might be a possibility, but I'm not sure how to
> operate on a list of lists with sets.

This is a job for... duhn-duhn-DAAAAH! Captain CHAOS!

Er... I mean itertools.groupby.

I took the liberty of not assuming the alist was sorted already.
This could be a one-liner if you wanted to be evil.

def bundle_alist(seq):
    """ Bundle together some alist tails. 
    
    >>> seq = [['a', '13'], ['a', '3'], ['b', '6'], ['c', '12'], ['c', '15'], ['c', '4'], ['d', '2'], ['e', '11'], ['e', '5'], ['e', '16'], ['e', '7']]
    >>> bundle_alist(seq)
    [['a', ['13', '3']], ['b', ['6']], ['c', ['12', '15', '4']], ['d', ['2']], ['e', ['11', '5', '16', '7']]]

    """
    from itertools import groupby
    def key_func(t):
        return t[0]
    groups = groupby(sorted(seq, key=key_func), key_func)
    seq = []
    for item in groups:
        seq.append([item[0], [a[1] for a in item[1]]])
    return seq


-- 
Neil Cerutti
Music gets more chromatic and heavy towards the end of the century. One of the
popular questions of the day was, "Why?" --Music Lit Essay



More information about the Python-list mailing list