python - 在长列表中查找多个元素的索引

标签 python

我有一个很长的 lst 包含独特的元素。我想设计一个将元素列表作为输入的函数,它可以有效地返回索引列表。我们假设找到索引所需的项目都在 lst 中。

这是一个例子:

lst = ['ab','sd','ef','de']
items_to_find = ['sd', 'ef', 'sd']
>>> fo(lst, items_to_find)  
# Output: [1,2,1]

我有自己的一种解决方案,但它看起来效率较低。

>> [lst.index(x) for x in items_to_find]

因为lst很长,我需要一个非常快的算法来解决它。

最佳答案

首先创建一个包含列表中每个项目的索引位置的字典(您声明所有项目都是唯一的,因此没有重复键的问题)。

然后用字典查找每一项的索引位置,平均时间复杂度O(1)。

my_list = ['ab', 'sd', 'ef', 'de']
d = {item: idx for idx, item in enumerate(my_list)}

items_to_find = ['sd', 'ef', 'sd']

>>> [d.get(item) for item in items_to_find]
[1, 2, 1]

关于python - 在长列表中查找多个元素的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48329879/

相关文章:

python - 使用 Python pandas 从另一个列驱动列

python pandas : Why can't I use both index_col and usecols in the same read_csv statement ? 引发 valueError

python - Pandas 定位 DataFrame 矩阵的最小值 : index, col

Python 日志记录 : Group logs which belong to one request

python - 使用 python 的 Electron 应用程序抛出 zmq.node 错误

python - 向 cp_model、ortools 添加多项选择约束

python - 将输入分解为列出的频率

python - GAE Python GCS 文件名访问旧文件

python - Django 。 TemplateDoesNotExist 在自定义小部件的情况下

java - ANTLR 是否提供语义