Create index list for np.split from the list that already has number for each section

后端 未结 1 1211
情话喂你
情话喂你 2021-01-27 22:40

I have two lists of numbers

list = [1,2,3,4,5,6,7,8,9]
number = [3,2,1,3]

I want to create index for np.split from number

1条回答
  •  盖世英雄少女心
    2021-01-27 23:14

    Approach #1

    If we want to use np.split resulting in a list of arrays, we need to use np.cumsum on those indexes to give us indices where we need to split the input list -

    np.split(list1, np.cumsum(number)[:-1])
    

    Sample run -

    In [36]: list1 = [1,2,3,4,5,6,7,8,9]
        ...: number = [3,2,1,3]
        ...: 
    
    In [37]: np.split(list1, np.cumsum(number)[:-1])
    Out[37]: [array([1, 2, 3]), array([4, 5]), array([6]), array([7, 8, 9])]
    

    Approach #2

    To have a list of lists, another approach with a loop comprehension again using cumsum -

    idx = np.r_[0,np.cumsum(number)]
    out = [list1[idx[i]:idx[i+1]] for i in range(len(idx)-1)]
    

    Sample run -

    In [45]: idx = np.r_[0,np.cumsum(number)]
    
    In [46]: [list1[idx[i]:idx[i+1]] for i in range(len(idx)-1)]
    Out[46]: [[1, 2, 3], [4, 5], [6], [7, 8, 9]]
    

    0 讨论(0)
提交回复
热议问题