如何在python列表中找到连续项的组?

a.l*_*x.n 2 python

我有一个这样的排序列表 [1,2,3,4,6,7,8,9,10,12,14]

我查找了不同的类似解决方案,但在我的情况下它们不提供帮助

我希望此列表以这种方式输出, [ [1,4], [6,10], [12], [14] ]
因此基本上是一个序列的开头和结尾的列表的清单。老实说看起来很简单,但是我现在有点坚持。任何帮助将不胜感激 !

Dev*_*ngh 6

您可以在此使用more_itertools.consecutive_groups网址https://pypi.org/project/more-itertools/

from more_itertools import consecutive_groups

#Get the groupings of consecutive items
li = [list(item) for item in consecutive_groups([1,2,3,4,6,7,8,9,10,12,14])]
#[[1, 2, 3, 4], [6, 7, 8, 9, 10], [12], [14]]

#Use the result to get range groupings
result = [ [item[0],item[-1]] if len(item) > 1 else [item[0]] for item in li]

print(result)
#[[1, 4], [6, 10], [12], [14]]
Run Code Online (Sandbox Code Playgroud)