I am trying to find the closest number to 5 in set b. This is my code.
b={1,2,45,65,3,2,8} one=5 a=set() for x in b: c=abs(x-one) a.add(c) print(min(a))
Advertisement
Answer
You can use the key
argument to min
to achieve this:
b = {1,2,45,65,3,2,8} target = 5 result = min(b, key=lambda x: abs(x - target))