Creating a list within a list in Python

前端 未结 5 1334
挽巷
挽巷 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 also do it like this:

    values = [0, 1, 2, 3, 4, 5, 351, 0, 1, 2, 3, 4, 5, 6, 750, 0, 1, 2, 3, 4, 5, 559]
    
    # Find all indices whose element is 0.
    indices = [index for index, value in enumerate(values) if value==0] + [len(values)]
    
    # Split the list accordingly
    values = [values[indices[i]:indices[i+1]] for i in range(len(indices)-1)]
    
    print(values)
    

    Output:

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

提交回复
热议问题