+-

参见英文答案 > Identify groups of continuous numbers in a list 12个
我有一个包含数据的列表:
我有一个包含数据的列表:
[1, 2, 3, 4, 7, 8, 10, 11, 12, 13, 14]
我想打印出连续整数的范围:
1-4, 7-8, 10-14
是否有内置/快速/有效的方法来做到这一点?
最佳答案
从 the docs开始:
>>> from itertools import groupby
>>> from operator import itemgetter
>>> data = [ 1, 4,5,6, 10, 15,16,17,18, 22, 25,26,27,28]
>>> for k, g in groupby(enumerate(data), lambda (i, x): i-x):
... print map(itemgetter(1), g)
...
[1]
[4, 5, 6]
[10]
[15, 16, 17, 18]
[22]
[25, 26, 27, 28]
您可以相当容易地调整它以获得一组打印范围.
点击查看更多相关文章
转载注明原文:python – 检测列表中的连续整数 - 乐贴网