data = [0.2, 6.4, 3.0]
bins = [(0.0, 1.0), (1.0, 4.0), (4.0, 10.0)] # assumed (lower, upper] format
cats = []
for elem in data:
for idx, bounds in enumerate(bins, start=1):
if bounds[0] < elem <= bounds[1]:
cats.append(idx)
break
else:
raise ValueError('No bin for {}'.format(elem))
2 回答
numpy has nice support for this无需编写
for
循环:如果你坚持
for
循环,只需迭代元素到bin和bin:以上使用元组来指定bin范围(如您的示例),但这在技术上并不必要(例如
numpy
代码) . 您可以只存储截止值并比较cutoffs[:-1]
中的相邻元素 .这里's a solution that should run faster if you have a very large list of ranges. It uses python' s
bisect
模块执行binary search以快速查找项目所属的范围 .对于这个例子,我使用范围2..5,7..9和13..13 .
代码检查0到14之间的所有数字是否都在提供的范围之一 .
代码:
输出: