简体   繁体   中英

Python find indices of elements in one list that are not in the other list

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

I want the indices of elements in list_1 that are not in list_2 . Here I would expect

[1, 4]

For my case, list_2 is a subset of list_1 and all elements are unique. Is there a better way to do this without using explicit loops?

You can use a conditional list comprehension:

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

This solution has a time complexity of O(n*m) . For bigger lists, it makes sense to convert list_2 to a set as it is much faster to search in a set . The following solution is O(n) :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM