【问题标题】:Split an array in python using indexes from a list使用列表中的索引在python中拆分数组
【发布时间】:2019-04-12 23:47:26
【问题描述】:

我在 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 中做到这一点?

【问题讨论】:

    标签: python python-3.x list numpy indexing


    【解决方案1】:

    您可以使用带有切片的列表推导式,使用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]]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-08
      • 2020-05-02
      • 1970-01-01
      • 1970-01-01
      • 2019-01-17
      • 2014-05-24
      相关资源
      最近更新 更多