Reputation: 247
Say I have a list like this:
lst = [1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0,
1, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0,
1, 0, 0, 0, 0, 0, 2, 0, 0]
I intended to split it into multiple sub-lists heading by 1:
new_lst = [[1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0],
[1, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0],
[1, 0, 0, 0, 0, 0, 2, 0, 0]]
This is how I render it for now and it worked fine. Is there any simplier way to do it? Like itertools however I couldn't think of how at this moment.
one_list = []
for i, j in enumerate(lst):
if j == 1:
one_list.append(i)
new_list = []
for i in range(len(one_list)-1):
head = one_list[i]
tail = one_list[i+1]
new_list.append(flag[head:tail])
Upvotes: 4
Views: 73
Reputation: 5590
more_itertools.split_before
will do exactly that
lst = list(more_itertools.split_before(lst, lambda x : x == 1))
# [[1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0], [1, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 2, 0, 0]]
Upvotes: 6