检查两个浮点数是否在给定的范围列表中

时间:2018-09-07 11:36:27

标签: python comparison

我有两个浮点数no_ano_b,还有两个范围,分别表示为两个元素列表,分别包含上下边界。

我要检查数字是否都在以下范围之一内:[0, 0.33][0.33, 0.66][0.66, 1.0]

如何用python代码整齐地编写该语句?

5 个答案:

答案 0 :(得分:6)

如果您只想获得TrueFalse的结果,请考虑以下内容。

>>> a = 0.4
>>> b = 0.6
>>> 
>>> ranges = [[0,0.33], [0.33,0.66], [0.66,1.0]]
>>> 
>>> any(low <= a <= high and low <= b <= high for low, high in ranges)
True

如果您要检查任意数量的数字(不仅是ab),可以将其概括为:

>>> numbers = [0.4, 0.6, 0.34]
>>> any(all(low <= x <= high for x in numbers) for low, high in ranges)
True

答案 1 :(得分:1)

赞:

RANGES = [[0,0.33], [0.33,0.66], [0.66,1.0]]


def check(no_a, no_b):
    for rng in RANGES:
        if rng[0] < no_a < rng[1] and rng[0] < no_b < rng[1]:
            return True
    else:
        return False


print(check(.1, .2))
print(check(.1, .4))

输出为:

True
False

或者这样:

no_a, no_b = .1, .2
print(any(rng[0] < no_a < rng[1] and rng[0] < no_b < rng[1] for rng in RANGES))
no_a, no_b = .1, .4
print(any(rng[0] < no_a < rng[1] and rng[0] < no_b < rng[1] for rng in RANGES))

输出为:

True
False

答案 2 :(得分:0)

看看db_and

将您的no_ano_b放入数组中,并检查所有事件是否都通过了您的语句。


第二编辑: 如所指出的,内置的all函数优于此小型数据集的numpy版本,因此已删除了numpy的用法:

ranges = [[0,0.33], [0.33,0.66], [0.66,1.0]]

for i in range(len(ranges)):
    if all([ranges[i][0] < no_a < ranges[i][1], 
            ranges[i][0] < no_b < ranges[i][1]]):
        print('Both values are in the interval of %s' %ranges[i])

将打印出两个值都属于的范围。

答案 3 :(得分:0)

使用广播进行数字键

import numpy as np

check = np.array([[0.4], [0.6]])
ranges = np.array([[0,0.33], [0.33,0.66], [0.66,1.0]])

((check >= ranges[:, 0]) & (check <= ranges[:, 1])).all(0).any()

True

详细信息

check >= ranges[:, 0]

#  0.00  0.33  0.66     <
[[ True  True False]  # 0.4
 [ True  True False]] # 0.6

check <= ranges[:, 1]

#  0.33  0.66  1.00      >     
[[False  True  True]   # 0.4
 [False  True  True]]  # 0.6

a = (check >= ranges[:, 0]) & (check <= ranges[:, 1])
a

#  0.00  0.33  0.66      <
#  0.33  0.66  1.00      >     
[[False  True False]   # 0.4
 [False  True False]]  # 0.6

为了使check的两个值都在一个范围对中,所有一列都必须为True

a.all(0)

[False  True False]

只要其中任何一个是True

a.all(0).any()

True

Numpy redux

但是,我们可以将checkranges转换为进行一次比较操作。

b = [1, -1]
(check.T * b >= ranges * b).all(1).any()

True

答案 4 :(得分:-1)

interval0 = (0.00, 0.33)
interval1 = (0.33, 0.66)
interval2 = (0.66, 1.00)

no_a = 0.1
no_b = 0.2

# checks for a single interval
def both_in_interval(no_a, no_b, interval):
    return (no_a >= interval[0] and no_a <= interval[1]) \
            and (no_b >= interval[0] and no_b <= interval[1])

# checks if it happens for 1 of them
print(any((both_in_interval(no_a, no_b, interval) for interval \
                            in [interval0, interval1, interval2])))