且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在python列表中找到最小的最近数字

更新时间:2023-11-26 08:09:10

您可以使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]