【发布时间】:2015-06-09 18:09:16
【问题描述】:
获取列表haystack 和needles
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 可能没有针,也可能包含很多。
【问题讨论】:
标签: python arrays list indexing element