简体   繁体   English

按数组切片

[英]Slicing by Array

I have an array as follows:我有一个数组如下:

 A =
 [[  1.   2.   3.   0.   0.   0.   0.]
 [  4.   5.   6.   0.   0.   0.   0.]
 [  7.   8.   9.   0.   0.   0.   0.]
 [ 10.  11.  12.   0.   0.   0.   0.]
 [ 13.  14.  15.   0.   0.   0.   0.]
 [ 16.  17.  18.   0.   0.   0.   0.]
 [ 19.  20.  21.   0.   0.   0.   0.]
 [ 22.  23.  24.   0.   0.   0.   0.]
 [ 25.  26.  27.   0.   0.   0.   0.]
 [ 28.  29.  30.   0.   0.   0.   0.]
 [  0.   0.   0.   0.   0.   0.   0.]
 [  0.   0.   0.   0.   0.   0.   0.]
 [  0.   0.   0.   0.   0.   0.   0.]
 [  0.   0.   0.   0.   0.   0.   0.]]

I also have a vector, v=[10, 3] , that tells me where I need to slice to obtain the submatrix at the top left-hand corner:我还有一个向量v=[10, 3] ,它告诉我需要在何处切片才能获得左上角的子矩阵:

 A[0:v[0], 0:v[1]] = 
[[  1.   2.   3.]
 [  4.   5.   6.]
 [  7.   8.   9.]
 [ 10.  11.  12.]
 [ 13.  14.  15.]
 [ 16.  17.  18.]
 [ 19.  20.  21.]
 [ 22.  23.  24.]
 [ 25.  26.  27.]
 [ 28.  29.  30.]]

Suppose I now have an n-dimensional array, A_n , with a submatrix at the top left-hand corner of it, as is the case above.假设我现在有一个 n 维数组A_n ,它的左上角有一个子矩阵,就像上面的例子一样。 Again, there is a vector v_n that tells me the range of my submatrix.同样,有一个向量v_n告诉我我的子矩阵的范围。

How do I slice the n-dimensional array with the vector without writing each index range by hand ie A_n[0:v_n[0], 0:v_n[1], 0:v_n[2] ...] ?如何在不手动写入每个索引范围的情况下使用向量切片 n 维数组,即A_n[0:v_n[0], 0:v_n[1], 0:v_n[2] ...]

You can construct a tuple of slice objects (which the colon representation basically represent) through a mappinng:您可以通过映射构造slice对象(冒号表示基本上代表)的元组:

A_n[tuple(map(slice, V_n))]

So if V_n = [10, 3] , we will pass it:所以如果V_n = [10, 3] ,我们将传递它:

>>> tuple(map(slice, [10, 3]))
(slice(None, 10, None), slice(None, 3, None))

This is basically a desugared version of what [:10, :3] means.这基本上是[:10, :3]含义的脱糖版本。

I think it is enough to convert A_n into a numpy array, and then slice it using a list comprehension:我认为将A_n转换为 numpy 数组,然后使用列表理解对其进行切片就足够了:

A_n = np.array(A_n)

A_sliced = A_n[[slice(i) for i in v_n]]

Check the below code:检查以下代码:

A = [[1., 2., 3., 0., 0., 0., 0.], [4., 5., 6., 0., 0., 0., 0.], [7., 8., 9., 0., 0., 0., 0.],
     [10., 11., 12., 0., 0., 0., 0.], [13., 14., 15., 0., 0., 0., 0.], [16., 17., 18., 0., 0., 0., 0.],
     [19., 20., 21., 0., 0., 0., 0.], [22., 23., 24., 0., 0., 0., 0.], [25., 26., 27., 0., 0., 0., 0.],
     [28., 29., 30., 0., 0., 0., 0.], [0., 0., 0., 0., 0., 0., 0.], [0., 0., 0., 0., 0., 0., 0.],
     [0., 0., 0., 0., 0., 0., 0.], [0., 0., 0., 0., 0., 0., 0.]]
n = [10,3]
arrayA = []
for i in range(0,n[0]):
    tempArray = []
    for j in range(0,n[1]):
        tempArray.append(j)
    arrayA.append(tempArray)
print(arrayA)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM