问题描述
我正在考虑几年前在Python中编写的代码,在某些时候,它必须通过索引列表的列表来获取一些元素。
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]
想知道是否有更多的pythonic的方式来做到。任何想法?
But I'm still wondering if there's an even more pythonic way to do it. Any ideas?
我想知道也可以使用numpy o任何其他数组库。
I would like to know also alternatives with numpy o any other array libraries.
推荐答案
值得看看的切片语法。在链接的页面中向下滚动,直到您转到索引,切片和迭代。
It's worth looking at NumPy for its slicing syntax. Scroll down in the linked page until you get to "Indexing, Slicing and Iterating".
这篇关于以某种方式获得矩阵的一些行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!