将一组整数转换为范围的最pythonic方法是什么(有问题已经converting a list of integers into range in python)但是有某种可接受的余量?
示例,我们有: 1,2,3,4,5,10,11,15,45,46,47,75,76,80,85
通常我们会得到: {1,5},{10,11},{15,15},{45,47},{75,76},{80,80},{85,85}
但我们希望允许20的保证金,因此只有当前一项和下一项之间的差异大于20时才会创建下一个范围
结果我们应该得到: {1,15},{45,47},{75,85}
答案 0 :(得分:1)
def to_ranges(nums):
rngs = []
start = nums[0]
curr = start
for n in nums[1:]:
if n > curr + 20:
rngs.append(range(start, curr + 1))
start = n
curr = n
rngs.append(range(start, curr + 1))
return rngs
>>> to_ranges([1, 2, 3, 4, 5, 10, 11, 15, 45, 46, 47, 75, 76, 80, 85])
[range(1, 16), range(45, 48), range(75, 86)]