python - 如何在Python列表中的每个元素的字典中找到最接近的键
问题描述
如果我有一本字典和一个看起来像的列表
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])])
推荐阅读
- python - Pandas 将嵌入 JSON 的 CSV 读取到数据框中
- ios - 单击消息后的 MessageKit 动画
- python - 为什么 Spark 在正确的代码上一直说“UnboundLocalError:分配前引用的局部变量”?
- html - 文本和图像对齐
- sql - 更新列中的时间戳值,使最新的时间戳是当前时间,同时保持行之间的相对时间差
- python - 如何在python中延迟调用lambda函数
- linux - 脚本在被 cron 或 udev 规则调用时不会下载文件
- angular - 面对“ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked”来显示/隐藏加载器
- c# - c#用户输入整数数组以查找特定数字
- python-3.x - 使用 Google Cloud Function 创建具有子目录路径的视频缩略图