Reputation: 21
I am trying to split a list into multiple ones. The original list lst
should be split on every element that is present in a second list, split_on
.
Example:
lst = [1, 2, 3, 4, 5, 6, 7, 8]
split_on = [3, 4, 7]
should yield:
[[1,2,3],[3,4],[4,5,6,7],[7,8]]
Note that both lst
and split_on
do not contain duplicate elements and that any item of split_on
is also an item of lst
. Finally, the order of the elements of split_on
can be random.
Upvotes: 1
Views: 56
Reputation: 15204
How about the following:
a = [1,2,3,4,5,6,7,8]
b = [4,3,7]
res = [[]]
for i in a:
res[-1].append(i)
if i in b:
res.append([i])
print(res) # [[1, 2, 3], [3, 4], [4, 5, 6, 7], [7, 8]]
Note that since b
is only used for membership tests and the order does not matter, you could consider converting it to a set
so that the approach scales better.
Upvotes: 2