简体   繁体   中英

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.

Similarly if my_no=3, output is equal to 1

I am new to python, so any help will be much appreciated. 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 :

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] . 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:

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

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