I have a list of numbers:
lst = [0, 1, 3, 4, 6, 9, 10, 11, 12, 13, 15]
and I would like to get a list of lists like so:
[[0, 1], [3, 4], [6], [9, 10, 11, 12, 13], [15]]
this means I would like to get the available continuous unique sequences from the first list.
What have I tried?
I have clunky function which iterates over each element and checks if the element is equal to the previous element +1 and appends it if that was the case.
>Solution :
You could try something like this:
def sequences(lst):
ret = [] # Initialise return list
j = 0 # Index at which the last break was made
for i, n in enumerate(lst[1:]): # Iterate through indexes and numbers
if n != (lst[i] + 1): # Check if there is a step which is not 1
ret.append(lst[j:i+1]) # If there is, append this portion to ret
j = i+1 # Update j
ret.append(lst[j:]) # Add the last portion
return ret # Return
print(sequences([0, 1, 3, 4, 6, 9, 10, 11, 12, 13, 15]))
Output: [[0, 1], [3, 4], [6], [9, 10, 11, 12, 13], [15]]