Splitting a list into uneven groups?

前端 未结 6 1983
北海茫月
北海茫月 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:10

    A numpythonic approach:

    >>> lst = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
    >>> sec = [2, 4, 5]
    >>> np.split(lst, np.cumsum(sec))
    [array([0, 1]), array([2, 3, 4, 5]), array([ 6,  7,  8,  9, 10]), array([11])]
    

    And here is a Python3.X approach using itertool.accumulate():

    >>> lst = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
    >>> sec = [2,4,6]
    >>> from itertools import accumulate
    >>> sec = list(accumulate(sec_lst))
    >>> sec = [0] + sec + [None] if sec[0] != 0 else sec + [None]
    >>> 
    >>> [lst[i:j] for i, j in zip(sec, sec[1:])]
    [[0, 1], [2, 3, 4, 5], [6, 7, 8, 9, 10], [11]]
    

提交回复
热议问题