繁体   English   中英

Python:如何获取间隔所属的浮点值?

[英]Python:How can I get a float value which interval belongs to?

我有一些像(0,1),[1,2),...,[9,10)之类的间隔。我想知道一个浮点值, eg 3.75 ,属于哪个间隔。我所做的是使左边界列表[0,1,...,9]和右边界列表[1,2,...,10] 我会在左边界找到比第一个大3.75的值3然后在右边界找到比第一个小3.754然后3.75属于区间[3,4)。找到3.75属于哪个区间的方法?

仅存储一个边界列表就足够了。 您可以使用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)

您也可以尝试使用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])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM