简体   繁体   English

如何找到列表中接近给定数字 Python 的*最小*数字?

[英]How to find the *smallest* number in the list that is close to a given number in Python?

I wanted to know if there is a way to find the smallest number in the list which is closest to a given number.我想知道是否有办法找到列表中最接近给定数字的最小数字。

Foe ex敌人

my_list=[1,10,15,20,45,56]
my_no=9

Output should be equal to 1 Explanation: since 9 comes between 1 and 10 and I want the smaller number, ie 1. Output 应该等于 1 解释:因为 9 介于 1 和 10 之间,我想要较小的数字,即 1。

Similarly if my_no=3, output is equal to 1同样如果my_no=3,output等于1

I am new to python, so any help will be much appreciated.我是 python 的新手,非常感谢您的帮助。 Thanks!谢谢!

List comprehension is another elegant way to do this.列表理解是另一种优雅的方式来做到这一点。

my_list=[1,10,15,20,45,56]
my_no = 9 
output = max([x for x in my_list if x<=my_no])
print(output) #1 

You can reduce from functools :您可以从functools reduce

from functools import reduce

i = reduce(lambda l, r: l if l <= my_no <= r else r, my_list)
print(i)

# Output
1

Test测试

# my_no = 18
>>> reduce(lambda l, r: l if l <= my_no <= r else r, my_list)
15

# my_no = 59
>>> reduce(lambda l, r: l if l <= my_no <= r else r, my_list)
56

Note: this code doesn't work if my_no < my_list[0] .注意:如果my_no < my_list[0]则此代码不起作用。 You have to check it before.你必须先检查一下。

If you want to stick to basics and want to approach it using for loop and if statement then it can be achieved as follows:如果你想坚持基础并想使用for loopif statement来处理它,那么它可以按如下方式实现:

my_list=[1,10,15,20,45,56]
given_number = 9

output=my_list[0]
for x in my_list:
  if(x < given_number and x > output):
    output= x

print(output)

# Output
1

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

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