给出5个范围
[(0., 0.), (0., 0.3), (0.3, 0.5), (0.5, 0.8), (0.8, 1.0)]
对应于:
-
[0.0,0.0]
-
(0.0,0.3)
-
(0.3,0.5)
-
(0.5,0.8)
-
(0.8,1.0)
以及输入浮点列表:
[0.5293113408538,
0.3105914215541,
0.7748290363338001,
0.7745464933980998,
0.17276995816109997,
0.83335888200110002,
0.0]
目标是将浮动框分成上面的范围并输出:
[3, 2, 3, 3, 1, 4, 0]
我试过这个:
score_ranges = [(0., 0.), (0., 0.3), (0.3, 0.5), (0.5, 0.8), (0.8, 1.0)]
x = [0.5293113408538,
0.3105914215541,
0.7748290363338001,
0.7745464933980998,
0.17276995816109997,
0.83335888200110002,
0.0]
binning = []
for i in x:
for j, (start, end) in enumerate(score_ranges):
if i == 0:
binning.append(0)
break
elif start < i <= end:
binning.append(j)
break
But is there a less verbose way to get the desired bining outputs?
Additionally, the zero range is sort of hard coded there because its lower bound is inclusive unlike the other classes, is there a better way to handle that?
1 回答
您可以使用bisect模块,但您必须稍微更改一下代码 . 将元组列表缩小到浮动列表 .