Python:如何获得一个间隔所属的浮点值?

时间:2016-11-01 07:36:00

标签: python

我有一些区间,如(0,1),[1,2),...,[9,10)。我想知道一个浮点值,e.g 3.75,属于哪个区间。我所做的是制作左边界列表[0,1,...,9]和右边界列表[1,2,...,10]。我会在左边界找到3.75大于3的第一个值。然后找到右边界中的第一个值3.75小于43.75然后3.75属于区间[3,4]。是否有更好的方法来查找var me = { name: "myname", age: "myage", bday: "mybday" }; me["newAt"] = "kkk"; //this adds at the end of the object 所属的区间?

2 个答案:

答案 0 :(得分:1)

仅存储一个边界列表就足够了。您可以使用bisect_right查找区间左边界的索引,然后index + 1是右边界:

import bisect

def find(num, boundaries):
    if boundaries[0] < num < boundaries[-1]:
        index = bisect.bisect_right(boundaries, num)
        return boundaries[index - 1], boundaries[index]
    return None

b = range(11)
CASES = [3.75, 0, 10, 5, 0.1, 9.9, 11, -1, 6.7]

for n in CASES:
    print('{} belongs to group {}'.format(n, find(n, b)))

输出:

3.75 belongs to group (3, 4)
0 belongs to group None
10 belongs to group None
5 belongs to group (5, 6)
0.1 belongs to group (0, 1)
9.9 belongs to group (9, 10)
11 belongs to group None
-1 belongs to group None
6.7 belongs to group (6, 7)

答案 1 :(得分:0)

您还可以尝试使用Python数学库中的floor()和ceil()函数来解决您的问题。

import math
lb = [0,1,2,3,4,5,6,7,8,9]
ub = [1,2,3,4,5,6,7,8,9,10]

inp = raw_input('Enter a number : ')
num = float(inp)

term = [[x, y] for x, y in zip(lb, ub) if int(math.floor(num)) == x and        int(math.ceil(num)) == y] 
if term == []:
    print str(num) + ' does not belong to any specified interval'
else:
    print str(num) + ' belongs to the interval ' + str(term[0])