本文介绍了查找一个列表中的任何元素出现在另一个列表中的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

获取列表haystackneedles

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

我需要生成在haystack中出现needles任何元素的索引列表.在这种情况下,这些索引分别是3、6和8

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]

不幸的是,在我的情况下,此解决方案给出了ValueError: 'W' is not in list.这是因为此处的区别在于needles的元素可能在haystack中多次出现或根本不出现.

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.

换句话说,haystack可能不包含针或可能包含许多针.

In other words, haystack may contain no needles or it may contain many.

推荐答案

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],它也会工作,因为您重复了元素.

Even if you used [haystack.index(i) for i in needles if i in haystack] it would not work as you have repeated elements.

进行st = set(needles)意味着我们有一个线性解决方案,因为集合查找为0(1),对于大输入而言,这将显着提高效率.

Making st = set(needles) means we have a linear solution as set lookups are 0(1) which for large input would be significantly more efficient.

这篇关于查找一个列表中的任何元素出现在另一个列表中的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-15 04:41