我有
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]]
谢谢! :)
答案 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)))