检测列表中的连续整数 [英] Detecting consecutive integers in a list
本文介绍了检测列表中的连续整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个包含数据的列表:
[1, 2, 3, 4, 7, 8, 10, 11, 12, 13, 14]
我想打印出连续整数的范围:
1-4, 7-8, 10-14
有没有内置/快速/有效的方法来做到这一点?
解决方案
来自 文档:
<预><代码>>>>从 itertools 导入 groupby>>>from 操作符导入 itemgetter>>>数据 = [ 1, 4,5,6, 10, 15,16,17,18, 22, 25,26,27,28]>>>对于 k, g 在 groupby(enumerate(data), lambda (i, x): i-x):...打印地图(itemgetter(1),g)...[1][4, 5, 6][10][15、16、17、18][22][25、26、27、28]你可以很容易地调整它以获得一组打印的范围.
I have a list containing data as such:
[1, 2, 3, 4, 7, 8, 10, 11, 12, 13, 14]
I'd like to print out the ranges of consecutive integers:
1-4, 7-8, 10-14
Is there a built-in/fast/efficient way of doing this?
解决方案
From 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]
You can adapt this fairly easily to get a printed set of ranges.
这篇关于检测列表中的连续整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文