Pythonic way to get some rows of a matrix

喜你入骨 提交于 2019-12-24 11:33:37

问题


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.


回答1:


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




回答2:


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




回答3:


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


来源:https://stackoverflow.com/questions/1105101/pythonic-way-to-get-some-rows-of-a-matrix

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!