简体   繁体   English

在字典中查找最接近的匹配数字(python)

[英]Find closest matching number in dictionary (python)

x = 115

freq_chart = {
'C1':'65.4063913251',
'C#1':'69.2956577442',
'D1':'73.4161919794',
'D#1':'77.7817459305',
'E1':'82.4068892282',
'F1':'87.3070578583',
'F#1':'92.4986056779',
'G1':'97.9988589954',
'G#1':'103.826174395',
'A1':'110',
'A#1':'116.5409403795',
'B1':'123.470825314'
}

I need to return the closest note name that x is closest to in freq_chart. 我需要返回在freq_chart中x最接近的音符名称。 In this example, x is closest to A#1. 在此示例中,x最接近A#1。 What is the syntax? 语法是什么? Thank you! 谢谢!

You can use min : 您可以使用min

>>> min(freq_chart, key=lambda y:abs(float(freq_chart[y])-x))
'A#1'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM