python列表纯大于零从小到大的整数,连续的数归一组,怎么划分?
python列表[1,2,4,6,7,8,9,12,15]分成[1,2],[4],[6,7,8,9],[12],[15]
python列表纯大于零从小到大的整数,连续的数归一组,怎么划分?
python列表[1,2,4,6,7,8,9,12,15]分成[1,2],[4],[6,7,8,9],[12],[15]
list = [1,2,4,6,7,8,9,12,15]
result = [[list[0]], ]
for n in list[1:]:
if n == result[-1][-1] + 1:
result[-1].append(n)
else:
result.append([n])
print(result)
输出:[[1, 2], [4], [6, 7, 8, 9], [12], [15]]