Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/359.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用列表中的索引在python中拆分数组_Python_Python 3.x_List_Numpy_Indexing - Fatal编程技术网

使用列表中的索引在python中拆分数组

使用列表中的索引在python中拆分数组,python,python-3.x,list,numpy,indexing,Python,Python 3.x,List,Numpy,Indexing,我有一个大小为3 x 7的二维数组,单位为numpy: [[1 2 3 4 5 6 7] [4 5 6 7 8 9 0] [2 3 4 5 6 7 8]] 我还有一个包含拆分点索引的列表: [1, 3] 现在,我想使用列表中的索引拆分数组,以便得到: [[1 2] [4 5] [2 3]] [[ 2 3 4] [5 6 7] [3 4 5]] [[ 4 5 6 7] [7 8 9 0] [5 6 7 8]] 如何在python中做到这一点?您可以使用列表理解和切片,使用zip成对提

我有一个大小为3 x 7的二维数组,单位为numpy:

[[1 2 3 4 5 6 7]
[4 5 6 7 8 9 0]  
[2 3 4 5 6 7 8]]
我还有一个包含拆分点索引的列表:

[1, 3]
现在,我想使用列表中的索引拆分数组,以便得到:

[[1 2]
[4 5]
[2 3]]

[[ 2 3 4]
[5 6 7]
[3 4 5]]

[[ 4 5 6 7]
[7 8 9 0]
[5 6 7 8]]

如何在python中做到这一点?

您可以使用列表理解和切片,使用
zip
成对提取索引

A = np.array([[1, 2, 3, 4, 5, 6, 7],
              [4, 5, 6, 7, 8, 9, 0],
              [2, 3, 4, 5, 6, 7, 8]])

idx = [1, 3]
idx = [0] + idx + [A.shape[1]]

res = [A[:, start: end+1] for start, end in zip(idx, idx[1:])]

print(*res, sep='\n'*2)

[[1 2]
 [4 5]
 [2 3]]

[[2 3 4]
 [5 6 7]
 [3 4 5]]

[[4 5 6 7]
 [7 8 9 0]
 [5 6 7 8]]