在 Python 中将范围分成 n 个相等范围的最佳方法

Best way to separate range into n equal ranges in Python

我有 N 范围内的元素总数和一些块 nb

我想将 N 分成 nb 个尽可能相等的范围,只有开始编号和结束编号。因此,例如,N=24nb=5 应该输出:

0,5 5,10 10,15 15,20 20,24

虽然 N=28nb=5 应该输出:

0,5 5,10 10,16 16,22 22,28  (the rest of `N/nb` division is equally distributed on the 3 last subranges)

根据一个评论,我有这个方法:

def partition(lst, n):
    division = len(lst) / n
    return [lst[round(division * i):round(division * (i + 1))] for i in range(n)]

def ranges(N, nb):
    return ["{},{}".format(r.start, r.stop) for r in partition(range(N), nb)]

>>> ranges(28, 5)
['0,6', '6,11', '11,17', '17,22', '22,28']

有更好的方法吗?

直接计算开始和结束数字肯定比切片 range 对象来获取它们更简单:

def ranges(N, nb):
    step = N / nb
    return ["{},{}".format(round(step*i), round(step*(i+1))) for i in range(nb)]

这并不比您的代码看起来更有效率,因为切片 range 对象只需要 O(1) 时间,所以您现有的代码已经是渐近最优的。我的版本可能会通过一些常数因子提高性能,但它可能很小。我确实认为我的版本也更清晰了,这可能比任何性能变化都更重要。