gatoatigrado gatoatigrado - 2 years ago 194
Python Question

split a list by a lambda function in python

Is there any version of

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

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

Answer Source

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]]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download