更新时间: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]