哔哔one
从文档:>>> 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]您可以很容易地调整它,以获取一组打印范围。
温温酱
这将完全按照您指定的方式打印:>>> nums = [1, 2, 3, 4, 7, 8, 10, 11, 12, 13, 14]>>> ranges = sum((list(t) for t in zip(nums, nums[1:]) if t[0]+1 != t[1]), [])>>> iranges = iter(nums[0:1] + ranges + nums[-1:])>>> print ', '.join([str(n) + '-' + str(next(iranges)) for n in iranges])1-4, 7-8, 10-14如果列表具有任何单个数字范围,则它们将显示为nn:>>> nums = [1, 2, 3, 4, 5, 7, 8, 9, 12, 15, 16, 17, 18]>>> ranges = sum((list(t) for t in zip(nums, nums[1:]) if t[0]+1 != t[1]), [])>>> iranges = iter(nums[0:1] + ranges + nums[-1:])>>> print ', '.join([str(n) + '-' + str(next(iranges)) for n in iranges])1-5, 7-9, 12-12, 15-18