对排序列表进行二进制搜索,找到列表中最接近用户提供的目标值的值 Python 3

Binary search of sorted list that find the closest value in list to targeted value provided by the user Python 3

有人可以帮助我如何访问所有浮点值并进行二进制搜索,以便如果匹配一个,它将输出列表中第二个的标题。例如,查看下面的输出,如果 0.369 匹配,它将输出自私。 谢谢。

到目前为止,列表的输出是 [['0.369', 'selfish', 'Future'] ['0.412', 'family', 'Future'] ] 列表根据十进制值从小到大排序 全部存储在 storage = [ ]

如果我对您的理解正确,这就是您要查找的内容:

def binary_search(storage, target):
    first = 0
    last = len(storage) - 1
    while first <= last:
        mid = (first + last) // 2
        value = float(storage[mid][0])
        if target == value:
            return storage[mid][1]
        elif value < target:
            first = mid + 1
        else:
            last = mid - 1
    return -1


storage = [["0.369", "selfish", "Future"], ["0.412", "family", "Future"]]

target = float(input("Please enter the desired float "))

result = binary_search(storage, target)
print(result)

请确保添加数据验证。例如,如果用户输入无效值 "abc"?

会发生什么