best way to take vertical slices from a matrix?

Olaf Delgado Friedrichs delgado at okeeffe-pc3.la.asu.edu
Wed Apr 25 03:57:47 EDT 2001


On Wed, 25 Apr 2001 00:04:09 +0100, mary <mary.stern at virgin.net> wrote:
>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)

Here's another way (who can say which one's the best):

>>> def vslice(a,j):
...   return apply(map, [None] + a)[j]
...
>>> a = [[1,2,3],[4,5,6],[7,8,9]]
>>> vslice(a,1)
(2, 5, 8)
>>>

If your rows can be tuples, you need something like

>>> def vslice(a,j):
...   return apply(map, [None] + map(tuple, a))[j]
...

instead of the above.

Finally, in Python 2.x, you can (and probably should) do something like

>>> def vslice(a, j):
...   return [a[i][j] for i in range(len(a))]
...

Olaf



More information about the Python-list mailing list