繁体   English   中英

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

[英]Split an array in python using indexes from a list

我在 numpy 中有一个大小为 3 x 7 的二维数组:

[[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]]

暂无
暂无

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

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