我有一个带有x,y值的元组列表。我想在列表中找到最接近的x值的索引。以下是我的代码。
# list of coords
a = [(376,220),(350,218),(324,216),(298,214),(271,211),(245,210),(219,208),(192,205),(166,204)]
to_find = (190,210)
#grab a new list with only x axis elements
lst = []
for i in range(len(a)):
lst.append(a[i][0])
#list of all x coordinates
print(lst)
#find the min closest element
def min_closest(lst,K):
return lst[min(range(len(lst)),key=lambda i: abs(lst[i] - K))]
#print the corresponding index
print(lst.index(min_closest(lst,to_find[0])))
我用x值制定了一个新列表。最后,我将搜索列表的x值与x列表进行了比较,以找到最接近的可能元素。后来我抓住了它的索引。有什么有效的方法吗?