简体   繁体   English

找到与列表中给出的数字最接近的数字 ~ Python

[英]Find The Closest Number To Numbers Given In A List ~ Python

How would you find the closest number in comparison to numbers given in a list?与列表中给出的数字相比,您将如何找到最接近的数字?

This is what I have tried so far, but it has been unsuccessful:这是我迄今为止尝试过的,但没有成功:

setted_list = [2,9,6,20,15]
value_chosen = 17

while True:
    final_value = setted_list[0]
    if setted_list[1] - value_chosen < setted_list[0] - value_chosen:
        final_value = setted_list[1]
    if setted_list[2] - value_chosen < setted_list[1] - value_chosen:
        final_value = setted_list[2]
    if setted_list[3] - value_chosen < setted_list[2] - value_chosen:
        final_value = setted_list[3]
    if setted_list[4] - value_chosen < setted_list[3] - value_chosen:
        final_value = setted_list[4]
print(final_value)

My output is always what is inside the value of setted_list[2] .我的输出始终是setted_list[2]值内的内容。 Where have I gone wrong in my algorithm?我的算法哪里出错了?

The loop while True: never break ... you need to find the end point.循环while True: never break ... 你需要找到终点。

maybe you wanted to do something like :也许你想做这样的事情:

>>> l=max(setted_list)
>>> for i in setted_list:
...     if abs(i-value_chosen)<l:
...             l=abs(i-value_chosen)
...             final_value=i
... 
>>> final_value
15

you can also do something like :您还可以执行以下操作:

>>> setted_list = [2,9,6,20,15]
>>> value_chosen = 17
>>> min(setted_list, key=lambda x:abs(x-value_chosen))
15

Here's a nice, clean simple one-liner: check this out you'll hopefully learn something new 😊 (@ the OP)这是一个漂亮、干净、简单的单线:看看这个,你会希望学到一些新东西😊(@ OP)

print min(setted_list, key = lambda x: abs(x-value_chosen))

If you're new to lambda functions, here's a simple intro:如果您不熟悉 lambda 函数,这里有一个简单的介绍:

f = lambda x: x**2+1

means exactly the same thing to a beginner as对初学者来说意味着完全相同的事情

def f(x): return x**2+1

Where x**2 could be generalized to any function of x, instead of just x²+1.其中 x**2 可以推广到 x 的任何函数,而不仅仅是 x²+1。

If you are too new to understand lambda functions yet,如果你还不太了解 lambda 函数,

   minimum = float("inf")
   setted_list = [2,9,6,20,15]
   value_chosen = 17
   for val in setted_list:
       if abs(val - value_chosen) < minimum:
           final_value = val
           minimum = abs(val - value_chosen)


   print final_value
l = [2,9,6,20,15]
val = 17

min_d = max(l) - val
closest_num = -1
for i in l:
    if abs(i - val) < min_d:
        min_d = abs(i-val)
        closest_num = i

print(closest_num)  
#>>> 15

here i use abs() to determine the closest value by substracting it from the original value在这里我使用abs()通过从原始值中减去它来确定最接近的值

slist = [2,9,6,20,15]
value = 17

def closest_value(value, iterable):
    storage = []
    for i in iterable:
        storage.append((abs(value-i),i))
    result = min(storage)
    return print(result[1])

closest_value(value,slist)
15

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

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