best way to take vertical slices from a matrix?

Alex Martelli aleaxit at yahoo.com
Wed Apr 25 05:40:37 EDT 2001


"mary" <mary.stern at virgin.net> wrote in message
news:9c50pc$5vtg$1 at sp15at20.hursley.ibm.com...
> I have a simple problem and am interested to find
> the 'best' way to do this in python:
>
> Given a list such as:
>
> x[0] = (1,2,3)
> x[1] = (4,5,6)
> x[2] = (7,8,9)
>
> what's the best way to 'take vertical slices' from this
> matrix, ie end up with:
>
> y[0] = (1,4,7)
> y[1] = (2,5,8)
> y[2] = (3,6,9)

List comprehensions may be simplest:

    y = [ [x[i][j] for j in range(3)] for i in range(3) ]

but they'll give you lists, not tuples as in your example's
notation; you'll have to explicitly use the tuple builtin
for transformation if you do require tuples.


Alex







More information about the Python-list mailing list