有什么方法可以检查某个值附近的值是否在字典的键中?

Is there any way to check if a value near a certain value is in the keys of the dictionary?

我需要检查一个值是否接近字典键中的某个值。 例如,我下面有一个字典 temp 并且有 4 个键; 1,10,20,30。 如果我这样编码,它就有意义了。

temp = {1:2, 10:4, 20:5, 30:12}
10 in temp.keys()
>> True

15 in temp.keys()
>> False

但是如果我这样编码,它会显示出我没有预料到的结果。因为 x+1 是 10 并且这个值肯定在字典的键中。

x = 9
(x-2 or x-1 or x or x+1 or x+2) in temp.keys()
>>False

我错过了什么吗?我想知道如何解决这个问题。请帮我 谢谢

您可以使用 any:

>>> temp = {1: 2, 10: 4, 20: 5, 30: 12}
>>> x = 9
>>> any(val in temp.keys() for val in (x - 2, x - 1, x, x + 1, x + 2))
True
>>> any(x + dx in temp.keys() for dx in range(-2, 2 + 1))
True
>>> any(val in temp.keys() for val in range(x - 2, x + 3)))
True
Input: 1 or 2 or 3
Output: 1

Input: 1 and 2 and 3
Output: 3

从上面的例子可以看出。 or 给出第一个值,and 给出最后一个值。

您遇到的问题是因为以下行:

(x-2 or x-1 or x or x+1 or x+2)

这一行不作为布尔表达式。相反,它会为您提供 x - 2 的任何值。在您的情况下,它将是 77 不在密钥中。所以,它是 False