The example looks like you want to split all numbers, where the last number must be
n - 1
and the
0
seems to be a special case. Maybe because it's the first value.
def group(iterable):
stack = []
for element in iterable:
if element == 0:
# special case 0
yield [0]
elif stack and stack[-1] + 1 != element:
# stack is not empty and last element is
# not incremented by 1
yield stack[:]
# clear the stack after yielding the last
# stack
stack.clear()
# append the element after
stack.append(element)
# yield the remaining stack
yield stack[:]
myList = [0, 1, 2, 3, 4, 3, 4, 1, 2]
print(list(group(myList)))
Output:
[[0], [0, 1, 2, 3, 4], [3, 4], [1, 2]]
With
more_itertools it's bit easier:
import more_itertools
myList = [0, 1, 2, 3, 4, 3, 4, 1, 2]
print(list(more_itertools.split_when(myList, lambda x,y: x + 1 != y)))
# or use a function instead of lambda
def condition(last_value, current_value):
return last_value + 1 != current_value
print(list(more_itertools.split_when(myList, condition)))
# and with the 0 as special case
def condition(last_value, current_value):
return last_value == 0 or last_value + 1 != current_value
print(list(more_itertools.split_when(myList, condition)))
Always if
condition
return a
True
, the list is splitted.
Documentation:
more_itertools.split_when