Assume you have a list of arbitrary elements like
['monkey', 'deer', 'lion', 'giraffe', 'lion', 'eagle', 'lion', 'fish']
which should be split into sublists after each element for which a given predicate, e.g.
is_lion(element)
returns True
. The above example should become
[['monkey', 'deer', 'lion'], ['giraffe', 'lion'], ['eagle', 'lion'], ['fish']]
Is there a pythonic way of doing it?
The easiest way is probably:
out = [[]]
for element in lst:
out[-1].append(element)
if predicate(element):
out.append([])
Note that this would leave an empty list at the end of out
, if predicate(element):
for the last element
. You can remove this by adding:
out = [l for l in out if l]
Just because we can, a functional one-liner:
from functools import reduce
reduce(lambda out, x: out[:-1] + [out[-1] + [x]] if not predicate(x) else out + [[x]], x, [[]])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With