Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pythonic way to split a list after elements for which a given predicate is true [duplicate]

Tags:

python

list

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?

like image 447
Mario Konschake Avatar asked Feb 14 '23 10:02

Mario Konschake


2 Answers

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]
like image 198
jonrsharpe Avatar answered Feb 16 '23 02:02

jonrsharpe


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, [[]])
like image 36
filmor Avatar answered Feb 16 '23 03:02

filmor