找出一个列表中任何元素在第二个列表中出现的索引

2024-04-27 16:16:15 发布

您现在位置:Python中文网/ 问答频道 /正文

获取列表haystackneedles

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

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

result = [3, 6, 8]

This question I found非常相似,并且用

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

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

换句话说,haystack可能不包含针头,也可能包含许多针头。


Tags: in元素列表forindex情况result解决方案
3条回答
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),对于大输入,这将显著提高效率。

如果指针不在haystack中,除了失败之外,index方法将只返回您要查找的元素的第一个位置,即使该元素出现多次(如示例中的'V')。你可以这样做:

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

枚举函数生成生成值元组的生成器-第一个是索引,第二个是值:

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

只要检查每个值是否在您的针列表中,并添加索引,如果它是。

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

相关问题 更多 >