找出列表中任何浮点数的两个最接近的数字

Orp*_*eon 3 python floating-point dictionary list

我有一个dict,浮点数作为键,对象作为值.我收到一个浮动,我想知道浮动的两个键之间.我怎么找到这个?

我在代码中的含义示例:

a = {}
a[1.2] = some_unimportant_instance
a[2.3] = some_other_unimportant_instance
a[2.6] = some_third_unimportant_instance
etc...

r = 2.5
# a[r] will not work
# I want something that returns the two numbers around r
# in this case, 2.3 and 2.6.
Run Code Online (Sandbox Code Playgroud)

use*_*136 7

第一个观察:dict-s对此不利.它们使用哈希实现,并且仅用于检索精确匹配的值.为了您的目的,您必须首先将dict转换为键列表.然后你可以使用像bisect这样的模块.

例:

import bisect
keys = sorted(a.keys())
index = bisect.bisect(keys, r)
if index >= 1:
    print keys[index - 1]
print keys[index]
Run Code Online (Sandbox Code Playgroud)

更新:根据Mark Dickinson的建议改进了代码.谢谢!