将浮点范围放入箱中

时间:2017-06-12 06:17:50

标签: python range floating binning

给出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

但是,获得所需的结果输出是否有一种不那么冗长的方式?

此外,零范围在那里是硬编码的,因为它的下限是包容性的,与其他类不同,是否有更好的方法来处理它?<​​/ strong>

1 个答案:

答案 0 :(得分:4)

您可以使用bisect模块,但您必须稍微更改一下代码。将元组列表缩小到浮动列表。

import bisect

score_ranges =  [0., 0.3, 0.5, 0.8, 1.0]
binning = []

x = [
    0.5293113408538,
    0.3105914215541,
    0.7748290363338001,
    0.7745464933980998,
    0.17276995816109997,
    0.83335888200110002,
    0.0]

for a in x:
    binning.append(bisect.bisect_left(score_ranges, a))