Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

split a list by a lambda function in python

Tags:

python

list

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]]
like image 540
gatoatigrado Avatar asked Jun 10 '11 06:06

gatoatigrado


2 Answers

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]]
like image 60
Ignacio Vazquez-Abrams Avatar answered Oct 26 '22 17:10

Ignacio Vazquez-Abrams


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]]
like image 24
Artsiom Rudzenka Avatar answered Oct 26 '22 19:10

Artsiom Rudzenka