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]
I want to create a new list that contains a list of elements from 0 up to a number.
Like :
new_values = [[0, 1, 2, ... , 351], [0, 1, 2, ... , 750], [0, 1, 2, ... , 559]]
The code that I did was this:
start = 0
new_values = []
for i,val in enumerate(values):
if(val == 0):
new_values.append(values[start:i])
start = i
However, what it returns this:
new_values = [[], [0, 1, 2, ... , 750], [0, 1, 2, ... , 559]]
How can I fix my code? It will really be a great help.
解决方案
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]]