Python way to get some rows of a matrix
I was thinking about code I wrote years ago in Python, at some point it only needed to get some elements by the 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 learned a little more since then, I would use a list comprehension like this:
[m[i] for i in row_indices]
But I'm still wondering if there is an even more pythonic way to do this. Any ideas?
I would like to know also alternatives with numpy o any other array libraries.
+1
source to share
3 answers
As Kurt said, it looks like 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]]
+2
source to share