在Python 3.5中,可以使用以下方法从数组中查找间隔范围:
def find_ranges(arr, interval):
ranges = []
start = arr[0]
end = arr[0]
for i in range(1, len(arr)):
if arr[i] - arr[i-1] == interval:
end = arr[i]
else:
ranges.append((start, end))
start = arr[i]
end = arr[i]
ranges.append((start, end))
return ranges
result = find_ranges(arr, 2)
for start, end in result:
print("Range: {} - {}".format(start, end))
完整的代码示例如下:
def find_ranges(arr, interval):
ranges = []
start = arr[0]
end = arr[0]
for i in range(1, len(arr)):
if arr[i] - arr[i-1] == interval:
end = arr[i]
else:
ranges.append((start, end))
start = arr[i]
end = arr[i]
ranges.append((start, end))
return ranges
arr = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
result = find_ranges(arr, 2)
for start, end in result:
print("Range: {} - {}".format(start, end))
这段代码将输出以下结果:
Range: 1 - 1
Range: 3 - 5
Range: 7 - 9
Range: 11 - 13
Range: 15 - 17
Range: 19 - 19
在这个例子中,我们从数组中查找间隔为2的范围,并将结果打印出来。每个范围由起始值和结束值组成。
领取专属 10元无门槛券
手把手带您无忧上云