直接使用zip
:
def range_sequence(start, stop, step):
return zip(range(start, stop, step), range(start+step, stop+step, step))
结果:
In [4]: list(range_sequence(0, 2000, 500))
Out[4]: [(0, 500), (500, 1000), (1000, 1500), (1500, 2000)]
请注意,这可能在末尾包含不需要的元素:
In [5]: list(range_sequence(0, 7864, 500))
Out[5]:
[(0, 500),
(500, 1000),
(1000, 1500),
(1500, 2000),
(2000, 2500),
(2500, 3000),
(3000, 3500),
(3500, 4000),
(4000, 4500),
(4500, 5000),
(5000, 5500),
(5500, 6000),
(6000, 6500),
(6500, 7000),
(7000, 7500),
(7500, 8000)]
这(7500, 8000)
对可能不是你想要的。如果你只是想停下来,(7000, 7500)
你可以简单地改变stop+step
成stop
。如果最后一对应该是(7500, 7864)
那么你必须做一些更复杂的事情:
def range_sequence(start, stop, step):
result = list(zip(range(start, stop, step), range(start+step, stop, step))
if (stop - start) % step != 0:
last_fst_elem = result[-1][-1] if result else start
result.append((last_fst_elem, stop))
return result
结果:
In [15]: range_sequence(0, 7864, 500)
Out[15]:
[(0, 500),
(500, 1000),
(1000, 1500),
(1500, 2000),
(2000, 2500),
(2500, 3000),
(3000, 3500),
(3500, 4000),
(4000, 4500),
(4500, 5000),
(5000, 5500),
(5500, 6000),
(6000, 6500),
(6500, 7000),
(7000, 7500),
(7500, 7864)]