我有
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]]
谢谢! :)
最佳答案
使用生成器函数(使用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)))