views:

184

answers:

3

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.

+4  A: 

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

João Marcus
I was thinking that maybe there was a nicer way to pass a sequence of index between the accessor brackets or something like that :-/
fortran
+4  A: 

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

Curt Hagenlocher
seemed promising, but nothing like I was searching :(
fortran
in what way does numpy not fit your need? to get a row you would just do M[i, :].
Autoplectic
yeah, now I've tried and it works, but I didn't find it in the docs so I thought the feature was missing...
fortran
Hmmm... I stopped at section 3.5 and the interesting stuff was at section 4.3.1
fortran
+2  A: 

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]]
tom10