gatoatigrado gatoatigrado - 7 months ago 61
Python Question

split a list by a lambda function in python

Is there any version of

split
that works on generic list types? For example, in Haskell

Prelude> import Data.List.Split
Prelude Data.List.Split> splitWhen (==2) [1, 2, 3]
[[1],[3]]

Answer

Nope. But you can use itertools.groupby() to mimic it.

>>> [list(x[1]) for x in itertools.groupby([1, 2, 3], lambda x: x == 2) if not x[0]]
[[1], [3]]