[Tutor] Help with lists

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Sat, 1 Dec 2001 16:05:46 -0800 (PST)

On Sat, 1 Dec 2001, Mike Yuen wrote:

> I've got a bit of a problem with lists that I need some help with.
> What I have is a pair of sub-elements (20 and A4) within each element such
> as: 
> [20, A4] <-- We'll call this pair "big element"
> There are over 20000 such big elements.  Not all of them are going to have
> a unique 1st sub-element (ie: the above big element has 20 as it's 1st
> sub element)
> What i'm trying to do is group them all the big elements with
> the same 1st subelements together.
> For example:
> [20, A4]
> [20, A2]
> [20, E] 
> Will make the following big element:
> [20, A4, A2, E]
> Can someone help me out?  I have to stick with lists as the structure
> meaning I can't use tuples or dictionaries.

Can we use dictionaries to help us construct the big elements?  If so,
then your problem isn't too bad.  Here's one idea: we can use a dictionary
to help group our lists by the first element:

def cluster(elements):
    holder = {}
    for e in elements:
        first, second = e
        holder[first] = holder.get(first, []) + [second]
    return holder.items()

Let's see how this works:

>>> cluster(l)
[(17, ['seventeen']), (20, ['A4', 'A2', 'E'])]

It's not perfect yet, but you can bend cluster() a bit to make it solve
your problem.