简体   繁体   中英

How to find which value is closest to a number in Python?

Is there any method in python to find which of two values is closet a given number?

Say i have two values such as 1.5 and 5.5, and i want to find which of them is closest to 3. Not using Lists

You can use min with a key function, the abs of their respective difference to the compare key:

min((1.5, 3.5), key=lambda x: abs(3-x))
# 3.5

I don't know if there's a built-in function for doing this, but its so easy to do your self, for example:-

Edit:-

Sorry i made some simple wrongs first because of i am using a mobile phone and i cant compile it but i fixed them:-

def closer(n1, n2, main):
    if(abs(main-n1)>abs(main-n2)):
        return n2
    else:
        return n1

print(closer(1.5, 5.5, 3))

#the result is 1.5

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