如果使用lambda

时间:2015-12-15 16:23:03

标签: python if-statement lambda list-comprehension

我有

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

我的代码行

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

listName拆分为[[0,1,2],[15,16,17],[2,3,4],[6,8,9]] 我希望只有当下一个数字小于前一个数字时才会发生拆分。即 我希望我的listName分成

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

谢谢! :)

1 个答案:

答案 0 :(得分:2)

使用生成器函数要容易得多,使用itertools.chain创建迭代器并展平列表:

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