Find indexes where any item in one list appears in another

Take the lists haystackandneedles

haystack = ['a', 'b', 'c', 'V', 'd', 'e', 'X', 'f', 'V', 'g', 'h']
needles = ['V', 'W', 'X', 'Y', 'Z']

I need to create a list of indexes at which any item needlesoccurs in haystack. In this case, these indices are 3, 6 and 8, therefore

result = [3, 6, 8]

This question I found is very similar and was pretty elegantly resolved with

result = [haystack.index(i) for i in needles]

Unfortunately, this solution gives ValueError: 'W' is not in listin my case. This is due to the fact that the difference here is that the element needlescan occur haystackseveral times or even absent.

In other words, it haystackmay not contain needles or may contain a lot.

+4
5
haystack = ['a', 'b', 'c', 'V', 'd', 'e', 'X', 'f', 'V', 'g', 'h']
needles = ['V', 'W', 'X', 'Y', 'Z']
st = set(needles)
print([i for i, e in enumerate(haystack) if e in st])
[3, 6, 8]

[haystack.index(i) for i in needles if i in haystack], , .

st = set(needles) , , 0(1), .

+9
needles_set = set(needles)
print [i for i, val in enumerate(haystack) if val in needles_set]
+2

, , index , , ( 'V' ). :

result = [idx for idx, val in enumerate(haystack) if val in needles]

, : - , - :

>>> print(list(enumerate(['a', 'b', 'c'])))

, , .

0

Definitely not the most efficient way, but you can do something like this:

result = []
i=0
while (i < len(haystack)):
    if (needles.count(haystack[i]) > 0):
        result.append(i)
    i+=1

What will give the result = [3, 6, 8]

0
source

You can try something like the following.

[Haystack.index(x) for x in needles if x in Haystack]

If x is not in haystack, then haystack.index(x)it will not be called, and no error should be thrown.

0
source

All Articles