简体   繁体   English

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

[英]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".输出是 25 而不是 15。问题是它总是给我“最接近的最大”而不是“最接近的最小”。

You could make the key also contain the number itself and use that for breaking ties:您可以使key还包含数字本身并使用它来打破关系:

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来解决它,它是稳定的:

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:尽管这仅在Python 2下需要,因为Python 3保证:

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) .这与其他保持排序稳定性的工具一致,例如sorted(iterable, key=keyfunc)[0]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 )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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