首页 > 解决方案 > 如何在Python列表中的每个元素的字典中找到最接近的键

问题描述

如果我有一本字典和一个看起来像的列表

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

times = [3, 8, 27]

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

[5, 5, 12]

因为列表中的第一个值 3 最接近键 10,所以键值 5 被添加到新列表中。有没有简单的方法来解决这个问题?

抱歉,如果这不是最好的措辞,我就是无法理解这一点。任何帮助,将不胜感激。

标签: python

解决方案


如果您不想使用 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])])

推荐阅读