关于数组:如何使用python中的列表切片二维矩阵?

How to slice a 2d matrix using lists in python?

本问题已经有最佳答案,请猛点这里访问。

在此示例中:

1
2
3
4
5
6
7
8
In [19]: a[[1,2,3],[1,2,3]].shape
Out[19]: (3,)

In [20]: a[1:4,1:4].shape
Out[20]: (3, 3)

In [21]: a.shape
Out[21]: (100, 100)

为什么Out [19]不是(3,3)?
我要使用列表的原因是因为我想做这样的事情:

1
a[[1,8,12],[34,45,50]].shape

因此结果将是(3,3)矩阵。


np.ix_

的完美用例

1
a[np.ix_([1,8,12],[34,45,50])]

演示

1
2
3
4
5
6
a = np.arange(5 * 5).reshape(5, 5)    
a[np.ix_([1, 2, 3], [1, 2, 3])]

array([[ 6,  7,  8],
       [11, 12, 13],
       [16, 17, 18]])