我有一个包含 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 列表进行比较,以找到最接近的可能元素。后来我捕获了它的索引。有什么有效的方法吗?
最佳答案
您完成了整个事情,但采取了额外的步骤:
a = [(376, 220), (350, 218), (324, 216), (298, 214), (271, 211), (245, 210), (219, 208), (192, 205), (166, 204)]
to_find = (190, 210)
ix = min(range(len(a)), key = lambda x: abs(a[x][0] - to_find[0]))
print(ix)
输出:
7
另一种方式,可能会更快:
a = [(376, 220), (350, 218), (324, 216), (298, 214), (271, 211), (245, 210), (219, 208), (192, 205), (166, 204)]
to_find = (190, 210)
min_diff, min_ix = 999999999, None
for ix, value in enumerate(a):
diff = abs(to_find[0] - value[0])
if diff < min_diff:
min_diff, min_ix = diff, ix
print(min_ix)
关于python - 获取索引值的有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58726309/