Pythonic way to get some rows of a matrix

Question:

I was thinking about a code that I wrote a few years ago in Python, at some point it had to get just some elements, by index, of a list of lists.

I remember I did something like this:

def getRows(m, row_indices):
    tmp = []
    for i in row_indices:
        tmp.append(m[i])
    return tmp

Now that I’ve learnt a little bit more since then, I’d use a list comprehension like this:

[m[i] for i in row_indices]

But I’m still wondering if there’s an even more pythonic way to do it. Any ideas?

I would like to know also alternatives with numpy o any other array libraries.

Asked By: fortran

||

Answers:

It’s the clean an obvious way. So, I’d say it doesn’t get more Pythonic than that.

Answered By: João Marcus

It’s worth looking at NumPy for its slicing syntax. Scroll down in the linked page until you get to "Indexing, Slicing and Iterating".

Answered By: Curt Hagenlocher

As Curt said, it seems that Numpy is a good tool for this. Here’s an example,

from numpy import *

a = arange(16).reshape((4,4))
b = a[:, [1,2]]
c = a[[1,2], :]

print a
print b
print c

gives

[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]
 [12 13 14 15]]
[[ 1  2]
 [ 5  6]
 [ 9 10]
 [13 14]]
[[ 4  5  6  7]
 [ 8  9 10 11]]
Answered By: tom10