1

如何将范围(n,n+2000)划分为大小为 j 的块。输出应类似于 [0,500],[500,1000],[1000,1500],[1500,2000]。但是如果 range(n,n+7864) ,那么我们如何将它们分成大致相等大小的块。

尝试的代码:

for a in range(1,500): 
    if (last<500):
        last=a+500 list.append([a,last]);
        a=last; 
    elif(last>500):
        list.append([list[len(list)-2][1],last element]) 
4

2 回答 2

4

直接使用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+stepstop。如果最后一对应该是(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)]
于 2013-11-02T16:11:44.340 回答
1

您可以使用生成器功能:

>>> import math
def solve(start, end, sep):
    prev = start
    for _ in xrange(int(math.ceil((end-start)/float(sep)))):
        _next = prev + sep
        yield [prev, min(_next, end)]
        prev = _next
...         
>>> list(solve(0, 7864, 500))
[[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]]
>>> list(solve(0, 2000, 500))
[[0, 500], [500, 1000], [1000, 1500], [1500, 2000]]
>>> list(solve(0, 1710, 500))
[[0, 500], [500, 1000], [1000, 1500], [1500, 1710]]
于 2013-11-02T16:16:36.020 回答