[英]N dimensional arrays - Python/Numpy
just wondering if there is any clever way to do the following. 只是想知道是否有任何聪明的方法来做到以下几点。
I have an N dimensional array representing a 3x3 grid 我有一个代表3x3网格的N维数组
grid = [[1,2,3],
[4,5,6],
[7,8,9]]
In order to get the first row I do the following: 为了获得第一行,我执行以下操作:
grid[0][0:3]
>> [1,2,3]
In order to get the first column I would like to do something like this (even though it is not possible): 为了获得第一列,我想做这样的事情(尽管不可能):
grid[0:3][0]
>> [1,4,7]
Does NumPy support anything similar to this by chance? NumPy是否偶然支持与此相似的任何内容?
Any ideas? 有任何想法吗?
Yes, there is something like that in Numpy: 是的,在Numpy中有类似的东西:
import numpy as np
grid = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
grid[0,:]
# array([1, 2, 3])
grid[:,0]
# array([1, 4, 7])
You can use zip
to transpose a matrix represented as a list of lists: 您可以使用
zip
转置表示为列表列表的矩阵:
>>> zip(*grid)[0]
(1, 4, 7)
Anything more than just that, and I'd use Numpy. 不仅如此,我还会使用Numpy。
To get the columns in Python you could use: 要获取Python中的列,您可以使用:
[row[0] for row in grid]
>>> [1,4,7]
You could rewrite your code for getting the row as 您可以重写代码以获取行
grid[0][:]
because [:]
just copies the whole array, no need to add the indices. 因为
[:]
只复制整个数组,不需要添加索引。
However, depending on what you want to achieve, I'd say it's better to just write a small matrix class to hide this implementation stuff. 但是,根据你想要实现的目标,我会说最好只写一个小矩阵类来隐藏这个实现的东西。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.