如何编写一个在整数列表中找到最接近值的函数?

时间:2017-03-22 07:17:28

标签: python

mylist = [1, 2, 3, 4, 5, 6, 7, 9, 10]
mynumber = 8

我想找到最接近mynumber的列表中的数字。我怎样才能编写能够做到这一点的函数?

我还是初学者,所以我怎么能只使用循环和if个数据呢?

2 个答案:

答案 0 :(得分:8)

考虑到你想要最接近的最小值。你也可以试试min函数:

min(myList, key=lambda x:abs(x-myNumber))

<强>更新

你也可以这样做:

mylist = [1, 2, 3, 4, 5, 6, 7, 9, 10]
mynumber = int(raw_input("enter num : "))

def closest(list, Number):
    temp = []
    for i in list:
        temp.append(abs(Number-i))

    return temp.index(min(temp))

a = closest(mylist, mynumber)
print "index is : ",a
print "Closet value is : ",mylist[a]

答案 1 :(得分:0)

迭代列表并比较当前最接近的数字

def takeClosest(myList, myNumber):
  closest = myList[0]
  for i in range(1, len(myList)):
    if abs(i - myNumber) < closest:
      closest = i
  return closest