list_1 = ["a", "b", "c", "d", "e"]
list_2 = ["a", "c", "d"]
我想要 list_1
中不在 list_2
中的元素的索引。在这里我希望
[1, 4]
就我而言,list_2
是 list_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/