interchanging rows and columns

Alex Martelli aleaxit at yahoo.com
Sat Oct 14 09:16:58 EDT 2000


"Ruud de Rooij" <*@spam.ruud.org> wrote in message
news:87lmvr3eo9.fsf at hobbes.home.ruud.org...
> johannes at zellner.org (Johannes Zellner) writes:
>
> > how can I turn
> >    [[1, 2, 3], [4, 5, 6]]
> > into
> >    [[1, 4], [2, 5], [3, 6]]
>
> The pythonic way to do these things seems to be to simply write a
> nested for loop, something like this:
>
> def transpose(m):
>   n = []
>   for i in range(len(m[0])):
>     r = []
>     for j in range(len(m)):
>       r.append(m[j][i])
>     n.append(r)
>   return n

Fine, but, in 2.0, an alternative...:

    def transpose(m):
        return [ [ subm[i] for subm in m ] for i in range(len(m[0])) ]


Alex






More information about the Python-list mailing list