A way to re-organize a list

marduk marduk at nbk.hopto.org
Thu Jul 19 17:41:41 CEST 2007


On Thu, 2007-07-19 at 15:05 +0000, beginner wrote:
> Hi Everyone,
> 
> I have a simple list reconstruction problem, but I don't really know
> how to do it.
> 
> I have a list that looks like this:
> 
> l=[ ("A", "a", 1), ("A", "a", 2), ("A", "a", 3), ("A", "b", 1), ("A",
> "b", 2), ("B", "a", 1), ("B", "b", 1)]
> 
> What I want to do is to reorganize it in groups, first by the middle
> element of the tuple, and then by the first element. I'd like the
> output look like this:
> 
> out=[
>    [    #group by first element "A"
>           [("A", "a", 1), ("A", "a", 2), ("A", "a", 3)], #group by
> second element "a"
>           [ ("A", "b", 1), ("A", "b", 2)], #group by second element
> "b"
>    ],
>    [   #group by first element "B"
>           [("B", "a", 1)],
>           [("B", "b", 1)]
>    ]
> ]

One way of doing it:

def group_by(i, my_list):
    d = {}
    for t in my_list:
        d[t[i]] = d.get(t[i], []) + [t]

    return d.values()





More information about the Python-list mailing list