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]]
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]]
One more solution:
output = [[]]
valueToSplit = 2
data = [1, 2, 3, 4, 1, 2, 3, 4, 5, 6, 2, 5, 2]
for i, val in enumerate(data):
if val == valueToSplit and i == len(data)-1:
break
output.append([]) if val == valueToSplit else output[-1].append(val)
print output # [[1], [3, 4, 1], [3, 4, 5, 6], [5]]
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