If statement in list comprehension with lambda

2019-07-19 00:51发布

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))]

is splitting listName into [[0,1,2],[15,16,17],[2,3,4],[6,8,9]] I want the split to happen only if the next number is less than the preceding number. i.e I want my listName to split into

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

Thanks! :)

1条回答
\"骚年 ilove
2楼-- · 2019-07-19 01:48

It is much easier to use a generator function, using itertools.chain to create an iterator and flatten 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)))
查看更多
登录 后发表回答