简体   繁体   中英

How to find the smallest closest number in a list in 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]

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".

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]

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] and heapq.nsmallest(1, iterable, key=keyfunc) .

Instead of this

min(list_of_numbers, key=lambda x:abs(x-number))
 

Try this :

number = 20
list_of_numbers = [4, 9, 15, 25]
list_of_numbers.sort(reverse=True)
min(list_of_numbers,key=lambda x : x - number > 0 )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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