Python:范围函数中的各种步长

时间:2018-02-20 14:44:08

标签: python-3.x range

下面的代码输出我想要的东西,但我想知道如何使它优雅,即单一:我如何优雅/简单地生成不同步长的矢量(用于分组数组的目的) )?

bins = [b for b in range(0,100,5)]
bins = numpy.append(bins, [b for b in range(100,200,10)]
bins = numpy.append(bins, [b for b in range(200,500,50)]
bins = numpy.append(bins, [b for b in range(500,2500,500)]

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

列出范围选项,然后迭代它们?

bins = []
for r in (range(0,100,5), range(100,200,10), range(200,500,50), range(500,2500,500)):
    bins = numpy.append(bins, [b for b in r])

甚至更整洁:

bins = []
for start, end, step in ((0,100,5), (100,200,10),(200,500,50), (500,2500,500)):
    bins = numpy.append(bins, [b for b in range(start, end,step)])

注意 - 这是一个通用答案 - 我不是numpy用户,所以我不知道是否有特定于numpy的做法这更有效率)。