If the expression is in a list comprehension with a lambda

I have

listName = [[0,1,2,15,16,17,2,3,4,6,8,9]] 

My line of code

 [list(g) for k, g in groupby(listName, key=lambda i,j=count(): i-next(j))] 

splits listName into [[0,1,2],[15,16,17],[2,3,4],[6,8,9]] I want the split to occur only if the following number less than the previous one. those. I want my listName split into

 [[0,1,2,15,16,17],[2,3,4,6,8,9]] 

Thanks!:)

+2
python lambda if-statement list-comprehension order
source share
1 answer

It is much easier to use the generator function, using itertools.chain to create an iterator and smooth your list:

 listName = [[0, 1, 2, 15, 16, 17, 2, 3, 4, 6, 8, 9]] from itertools import chain def split(l): it = chain(*l) prev = next(it) tmp = [prev] for ele in it: if ele < prev: yield tmp tmp = [ele] else: tmp.append(ele) prev = ele yield tmp print(list(split(listName))) 
+2
source share

All Articles