Take lists haystack
and needles
haystack = ['a', 'b', 'c', 'V', 'd', 'e', 'X', 'f', 'V', 'g', 'h']
needles = ['V', 'W', 'X', 'Y', 'Z']
I need to generate a list of the indices at which any element of needles
occurs in haystack
. In this case those indices are 3, 6, and 8 thus
result = [3, 6, 8]
This question I found is very similar and was rather elegantly solved with
result = [haystack.index(i) for i in needles]
Unfortunately, this solution gives ValueError: 'W' is not in list
in my case. This is because the difference here is that an element of needles
may occur in haystack
a number of times or not at all.
In other words, haystack
may contain no needles or it may contain many.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…