[英]Efficient way to grab an index value
我有一个带有 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)
Output:
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)
将a
转换为numpy.array
然后使用np.argmin
:
arr = np.array(a)
diffs = np.abs(arr - to_find)
arr[np.argmin(diffs[:, 0])]
#OUTPUT array([192, 205])
尝试使用scipy.spatial.distance.euclidean
:
from scipy.spatial.distance import euclidean
a = [(376, 220), (350, 218), (324, 216), (298, 214), (271, 211), (245, 210), (219, 208), (192, 205), (166, 204)]
to_find = (190, 210)
print(min(a, key = lambda x: euclidean(x, to_find)))
Output:
(192, 205)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.