4

just wondering if there is any clever way to do the following.

I have an N dimensional array representing a 3x3 grid

grid = [[1,2,3],
        [4,5,6],
        [7,8,9]]

In order to get the first row I do the following:

grid[0][0:3]
>> [1,2,3]

In order to get the first column I would like to do something like this (even though it is not possible):

grid[0:3][0]
>> [1,4,7]

Does NumPy support anything similar to this by chance?


Any ideas?

3 Answers 3

10

Yes, there is something like that in Numpy:

import numpy as np

grid = np.array([[1, 2, 3],
                 [4, 5, 6],
                 [7, 8, 9]])

grid[0,:]
# array([1, 2, 3])

grid[:,0]
# array([1, 4, 7])
Sign up to request clarification or add additional context in comments.

Comments

2

You can use zip to transpose a matrix represented as a list of lists:

>>> zip(*grid)[0]
(1, 4, 7)

Anything more than just that, and I'd use Numpy.

Comments

1

To get the columns in Python you could use:

[row[0] for row in grid]
>>> [1,4,7]

You could rewrite your code for getting the row as

grid[0][:]

because [:] just copies the whole array, no need to add the indices.

However, depending on what you want to achieve, I'd say it's better to just write a small matrix class to hide this implementation stuff.

4 Comments

Don't write your own matrix classes. Use good matrix classes already provided.
@eumiro: You're absolutely right. Do you have a specific class in mind?
@eumiro: Numpy seems to be a little overkill in many cases to me. As far as I can see one even has to install a binary.
there is a debian/ubuntu/(other) package for numpy. Once installed, serves always.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.