interchanging rows and columns

Alex Martelli aleaxit at yahoo.com
Sat Oct 14 12:08:39 EDT 2000


"Johannes Zellner" <johannes at zellner.org> wrote in message
news:slrn8ugrc2.7h7.johannes at kristine.zellner.org...
    [snip]
> >    def transpose(m):
> >        return [ [ subm[i] for subm in m ] for i in range(len(m[0])) ]
> >
> hmm. I also found a solution myself:
>     apply(lambda *x: map(None, *x), my_matrix)

This, like zip, gives a list of tuples, not a list of lists as originally
required.  (You may map list on the result to fix that).  I used
list comprehensions to make sure I did return lists...:-).


> It seems that one can really write unreadable code with python :-(

Of course one can.  Still, I don't find list comprehensions at all
unreadable.  With map, apply, lambda, etc, it's easier (IMHO)
to pack a bit too much power in too compact a space for easy
readability; list comprehensions, since all they ever do is build
a list out of its explicitly enumerated elements, are (again IMHO)
less prone to that.

It must be said that something you're familiar with is always
likely to be found "more readable" than something novel, and
list comprehensions may fall in both classes for different
readers.

Appropriate use of names can always help.  E.g., turn my
proposed code into...:

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

and I think it becomes more readable, because the role of
that only complicated subexpression 'range(len(m[0]))' is
clarified by naming it 'rowindices'.


Alex






More information about the Python-list mailing list