如何将列表项分组为 Python 中的顺序元组?

How to group list items into sequential tuples in Python?

我有一个列表,其中包含按升序排列的数字,例如

[0, 1, 3, 4, 6]

[2, 3, 4, 5]

我需要获取一个列表列表,其中包含作为范围项的元素,例如

[[start, end], [start, end]] 来自输入列表。

[[0, 1], [3, 4], [6, 6]]

[[2, 5]]

输入列表中不存在的元素应该放在哪里。

这是我试过的代码。但不确定如何获得它。

zers = [0, 1, 3, 4, 6]
ls = []
for i, j in enumerate(zers):
    if i!=len(zers)-1 and zers[i+1]==zers[i]+1:last=i;continue
    else:
        if i==0:ls.append([i,i])
        else:ls.append([last, i])
print(ls) 

它应该给 [[0, 1], [3, 4], [6, 6]] 但是给出 [[0, 1], [2, 3], [2, 4]]

请随时对我的代码进行任何修改或提供完全不同的解决方案。

我认为应该有一个来自现有库的函数,但不确定。如果您遇到这种情况,请告诉我。

使用more_itertools.consecutive_groups对连续元素进行分组,然后从组中获取第一个和最后一个元素:

import more_itertools as mit

iterable = [0, 1, 3, 4, 6]
x = [list(group) for group in mit.consecutive_groups(iterable)]

output = [[i[0],i[-1]] for i in x]
print(output)

输出:

[[0, 1], [3, 4], [6, 6]]