# A way to re-organize a list

Carsten Haese carsten at uniqsys.com
Thu Jul 19 17:27:34 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)]
>    ]
> ]

That's easy with the magic of itertools.groupby and operator.itemgetter:

>>> from itertools import groupby
>>> from operator import itemgetter
>>> from pprint import pprint
>>> first = itemgetter(0)
>>> second = itemgetter(1)
>>> l = [ ("A", "a", 1), ("A", "a", 2), ("A", "a", 3), ("A", "b", 1), ("A",
... "b", 2), ("B", "a", 1), ("B", "b", 1)]
>>> result = [[list(g2) for _,g2 in groupby(g1,second)] for _,g1 in groupby(l,first)]
>>> pprint(result)
[[[('A', 'a', 1), ('A', 'a', 2), ('A', 'a', 3)],
[('A', 'b', 1), ('A', 'b', 2)]],
[[('B', 'a', 1)], [('B', 'b', 1)]]]

HTH,

--
Carsten Haese
http://informixdb.sourceforge.net

```