如何在python列表中找到最小的最近数字 [英] How to find the smallest closest number in a list in python
本文介绍了如何在python列表中找到最小的最近数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道如何找到列表中与给定数字最接近的最小数字. 例如:
I want to know how can I find the smallest closest number in a list to a given number. For example:
number = 20
list_of_numbers = [4, 9, 15, 25]
我尝试过:
min(list_of_numbers, key=lambda x:abs(x-number))
输出是25,而不是15.问题是它总是给我最大的最近"而不是最小的最近".
The output is 25 and not 15. The problem is that it always gives me the "biggest closest" and not the "smallest closest".
推荐答案
您可以使key
也包含数字本身,并将其用于打破平局:
You could make the key
also contain the number itself and use that for breaking ties:
min(list_of_numbers, key=lambda x: (abs(x - number), x))
但是,您的行为很奇怪.这可能是一个错误.您可以使用稳定的sorted
来解决此问题:
Your behavior is strange, though. It might be a bug. You might be able to work around it by using sorted
, which is stable:
sorted(list_of_numbers, key=lambda x: abs(x - number))[0]
这篇关于如何在python列表中找到最小的最近数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文