Python 查找一个列表中不在另一个列表中的元素的索引

标签 python list

list_1 = ["a", "b", "c", "d", "e"]
list_2 = ["a", "c", "d"] 

我想要 list_1 中不在 list_2 中的元素的索引。在这里我希望

[1, 4]

就我而言,list_2list_1 的子集,所有元素都是唯一的。有没有更好的方法可以在不使用显式循环的情况下做到这一点?

最佳答案

您可以使用条件列表理解:

>>> [i for i, item in enumerate(list_1) if item not in list_2]
[1, 4]

此解决方案的时间复杂度为 O(n*m)。对于更大的列表,将 list_2 转换为 set 是有意义的,因为在 set 中搜索要快得多。以下解决方案是O(n):

>>> set_2 = set(list_2)
>>> [i for i, item in enumerate(list_1) if item not in set_2]
[1, 4]

关于Python 查找一个列表中不在另一个列表中的元素的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58848628/

相关文章:

python - 可以使用这个 soundex 编码的一些帮助

python - 使用 Panda read_csv 函数仅加载行列表 - Python

python - 使用 Pandas groupby 的 Mathematica GatherBy 函数

python - 如何从 Python 列表末尾删除 'None' 项

python - 迭代列表和文件读取

python - 使用 python 重新排列文本文件中的数据时遇到麻烦

python - Matplotlib:3 个图绘制成 2 行,单个图像居中

python - 如何按第一个元素对元组列表进行排序?

java - 查找双链表的中间节点数为偶数

Python 将字符串拆分/切片到列表中,同时保留分隔符