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

在Python中将范围分隔为n个相等范围的最佳方法,python,range,divide,Python,Range,Divide,我有N范围内的元素总数和nb范围内的块数 我想把N分成nb个尽可能相等的范围,只包括开始数和结束数。例如,N=24和nb=5应输出: 0,5 5,10 10,15 15,20 20,24 0,5 5,10 10,16 16,22 22,28 (the rest of `N/nb` division is equally distributed on the 3 last subranges) 当N=28和nb=5时,应输出: 0,5 5,10 10,15 15,20 20,24 0,5

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

我想把N分成nb个尽可能相等的范围,只包括开始数和结束数。例如,N=24和nb=5应输出:

0,5 5,10 10,15 15,20 20,24
0,5 5,10 10,16 16,22 22,28  (the rest of `N/nb` division is equally distributed on the 3 last subranges)
当N=28和nb=5时,应输出:

0,5 5,10 10,15 15,20 20,24
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']

有更好的方法吗

直接计算开始和停止数字肯定比切片范围对象获取它们更简单:

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

这并不像您的代码看起来那样高效,因为切片一个范围对象只需要O1次,所以您现有的代码已经是渐近最优的。我的版本可能会通过一些固定因素来提高性能,但它可能很小。不过,我确实认为我的版本也更加清晰,这可能比性能变化更重要。

这与这个问题有些相似: