Splitting a list into uneven groups?

前端 未结 6 1966
北海茫月
北海茫月 2020-12-14 20:47

I know how to split a list into even groups, but I\'m having trouble splitting it into uneven groups.

Essentially here is what I have: some list, let\'s call it

6条回答
  •  囚心锁ツ
    2020-12-14 21:15

    Using list-comprehensions together with slicing and sum() function (all basic and built-in tools of python):

    mylist = [1,2,3,4,5,6,7,8,9,10]
    seclist = [2,4,6]
    
    [mylist[sum(seclist[:i]):sum(seclist[:i+1])] for i in range(len(seclist))]
    
    #output:
    [[1, 2], [3, 4, 5, 6], [7, 8, 9, 10]]
    

    If seclist is very long and you wish to be more efficient use numpy.cumsum() first:

    import numpy as np
    cumlist = np.hstack((0, np.cumsum(seclist)))
    [mylist[cumlist[i]:cumlist[i+1]] for i in range(len(cumlist)-1)]
    

    and get the same results

提交回复
热议问题