mylist = [1, 2, 3, 4, 5, 6, 7, 9, 10]
mynumber = 8
我想找到最接近mynumber的列表中的数字。我怎样才能编写能够做到这一点的函数?
我还是初学者,所以我怎么能只使用循环和if
个数据呢?
答案 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