簡體   English   中英

如何在字典中為 Python 中的列表中的每個元素找到最接近的鍵

[英]How to find closest key in dictionary for each element in a list in Python

如果我有一本字典和一個看起來像的列表

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

times = [3, 8, 27]

我想根據哪個鍵最接近列表中的每個元素,使用字典中的值創建一個新列表。 所以在這個例子中,output 將是

[5, 5, 12]

因為列表中的第一個值 3 最接近鍵 10,所以鍵值 5 被添加到新列表中。 有沒有簡單的方法到 go 關於這個?

抱歉,如果這不是最好的措辭,我就是無法理解這一點。 任何幫助,將不勝感激。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM