Reputation: 19815
I have two list of integers, namely numbers
and delimiters
. I want to divide numbers
into chunks divided by delimiters
.
numbers = [10, 13, 7, 204, 129, 44, 12, 7, 17, 49, 216, 43, 16, 7, 7, 38, 29, 76, 54, 17, 39, 7, 17, 77, 7, 24, 19]
delimiters = [7,17,77]
result = [[10,13],[204, 129, 44, 12],[49, 216, 43, 16],[38, 29, 76, 54],[39],[24, 19]]
As already seen in the example, I want to split the list if I see one or multiple occurences of the delimiter
.
I can easily do it by a simple loop, but I am sure there should be a better, probably more Pythonic way of doing it. I also feel like itertools
is the way to go, however, I couldn't find a good function that could fit to this problem.
Upvotes: 1
Views: 94
Reputation: 251051
Here you go, using itertools.groupby
:
>>> from itertools import groupby
>>> [list(g) for k, g in groupby(numbers, delimiters.__contains__) if not k]
[[10, 13], [204, 129, 44, 12], [49, 216, 43, 16], [38, 29, 76, 54], [39], [24, 19]]
Upvotes: 6