split a list by a lambda function in python
Is there any version of sp开发者_开发百科lit
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]]
You can also create an iterator and use itertools.takewhile
to include all matching items and discard the delimiter:
>>> import itertools
>>> l = [1, 2, 3]
>>> a = iter(l)
>>> [[_]+list(itertools.takewhile(lambda x: x!=2, a)) for _ in a]
[[1], [3]]
@TigerhawkT3 answer isn't flawlessly, but i can't add a comment
when l = [1, 2, 2, 2, 2, 3, 4]
output [[1], [2], [2, 3, 4]]
seem "wrong", but he inspired me
import itertools
l = [1, 2, 2, 2, 2, 3, 4]
a = iter(l)
output = [[_] + list(itertools.takewhile(lambda x: x != 2, a)) for _ in a if _ != 2]
output = [[1], [3, 4], [123, 123]]
精彩评论