问题
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]
I tried this:
min(list_of_numbers, key=lambda x:abs(x-number))
The output is 25 and not 15. The problem is that it always gives me the "biggest closest" and not the "smallest closest".
回答1:
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))
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]
回答2:
Add the number from the list of numbers to the key, so it's taken into account.
min(list_of_numbers, key=lambda x: (abs(x - number), x))
Also if you want the first number from the list which matches the requirement, add the index to the key:
min(enumerate(list_of_numbers), key=lambda ix: (abs(ix[1] - number), ix[0]))[1]
Though this would only be needed under Python 2, because Python 3 guarantees that:
If multiple items are minimal, the function returns the first one encountered. This is consistent with other sort-stability preserving tools such as
sorted(iterable, key=keyfunc)[0]
andheapq.nsmallest(1, iterable, key=keyfunc)
.
来源:https://stackoverflow.com/questions/40271548/how-to-find-the-smallest-closest-number-in-a-list-in-python