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

问题描述

限时删除!!

Take 列表 haystackneedles

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

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

result = [3, 6, 8]

我发现的这个问题 非常相似,用

解决得相当优雅

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

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

换句话说,haystack 可能没有针,也可能有很多.

解决方案
haystack = ['a', 'b', 'c', 'V', 'd', 'e', 'X', 'f', 'V', 'g', 'h']针 = ['V', 'W', 'X', 'Y', 'Z']st = 设置(针)打印([i for i, e in enumerate(haystack) if e in st])[3, 6, 8]

即使您使用 [haystack.index(i) for i in Needs if i in haystack] 它也不起作用,因为您有重复的元素.

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

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.

解决方案
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]

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

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.

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

1403页,肝出来的..

09-09 01:17