如何在Python中为列表中的每个元素查找字典中最近的键

如何在Python中为列表中的每个元素查找字典中最近的键,python,Python,如果我有一本字典和一份清单 dict = {'10': 5, '25': 12, '40': 6, '55': 18} times = [3, 8, 27] 我想用字典中的值创建一个新列表,基于哪个键最接近列表中的每个元素。所以在这个例子中,输出是 [5, 5, 12] 因为列表中的第一个值3最接近键10,所以键值5将添加到新列表中。有没有一个简单的方法 对不起,如果这不是最好的措辞,我只是不能把我的头围绕着这个。任何帮助都将不胜感激。如果您不想使用numpy,您可以这样做: impor

如果我有一本字典和一份清单

dict = {'10': 5, '25': 12, '40': 6, '55': 18}

times = [3, 8, 27]
我想用字典中的值创建一个新列表,基于哪个键最接近列表中的每个元素。所以在这个例子中,输出是

[5, 5, 12]
因为列表中的第一个值3最接近键10,所以键值5将添加到新列表中。有没有一个简单的方法


对不起,如果这不是最好的措辞,我只是不能把我的头围绕着这个。任何帮助都将不胜感激。

如果您不想使用numpy,您可以这样做:

 import numpy as np

 dic = {'10': 5, '25': 12, '40': 6, '55': 18}

 times = [3, 8, 27]

 #create a array with the keys of the dictionarie, transformed in numbers
 keys = np.array([eval(i) for i in dic.keys()])

 for t in times:
      #here, we will create a list with the absolute value of the differences
      #and call the argsort function, wich return the index that sort the list,
      #and pick the first value
      closest = np.argsort(abs(keys-t))[0]

      #finally, the key is keys[closest]. But we need to transform back
      #in string
      print(dic[str(keys[closest])])

1.你在乎速度吗?2.如果是领带,你想怎么办?像d={4:4,6:6}和times=[5]。3.你有什么企图吗?