python - 获取索引值的有效方法

标签 python list search tuples

我有一个包含 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/

相关文章:

django - Django haystack 和 whoosh 的字符折叠

python - 使用Python从字符串中删除除数字以外的字符?

python - 在大循环 Pandas to_csv 中优化时间

list - 在 Kotlin 中对 MutableList 中的数据进行排序

list - 在 K 复合数的 Haskell 中创建无限列表

javascript - 如何从字符串数组中以任意顺序匹配并突出显示所有术语?

python - gensim.corpora.Dictionary 是否保存了词频?

python - 生成一个重新映射的 numpy 数组作为 View 。

java - 如何在java中声明匿名数组列表?

mysql - MySQL 中的全文搜索查询