Creating a list within a list in Python

前端 未结 5 1323
挽巷
挽巷 2021-01-21 05:48

I have a list named values containing a series of numbers:

values = [0, 1, 2, 3, 4, 5, ... , 351, 0, 1, 2, 3, 4, 5, 6, ... , 750, 0, 1, 2, 3, 4, 5, ... , 559]
         


        
5条回答
  •  庸人自扰
    2021-01-21 06:49

    You can group your elements with itertools.groupby based on the presence of 0 (which is falsy) and extract the sublists between 0 while appending the missing 0 with a list comprehension:

     [[0]+list(g) for k, g in groupby(values, bool) if k]
    

    Example:

    >>> from itertools import groupby
    >>> values = [0, 1, 2, 3, 4, 5 , 351, 0, 1, 2, 3, 4, 5, 6, 750, 0, 1, 2, 3, 4, 559]
    >>> [[0]+list(g) for k, g in groupby(values, bool) if k]
    [[0, 1, 2, 3, 4, 5, 351], [0, 1, 2, 3, 4, 5, 6, 750], [0, 1, 2, 3, 4, 559]]
    

提交回复
热议问题