【问题标题】:Find the indices at which any element of one list occurs in another查找一个列表的任何元素在另一个列表中出现的索引
【发布时间】:2015-06-09 18:09:16
【问题描述】:

获取列表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 可能没有针,也可能包含很多。

【问题讨论】:

    标签: python arrays list indexing element


    【解决方案1】:
    needles_set = set(needles)
    print [i for i, val in enumerate(haystack) if val in needles_set]
    

    【讨论】:

    • 如何在haystack中找到needles_set没有找到的索引?
    【解决方案2】:
    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),这对于大量输入会显着提高效率。

    【讨论】:

    • 绝对是将needles 放入集合的更好解决方案。哈希表查找肯定会提高性能。
    • @Anzel,defo,显然在这里不会有太大区别,但在大型数据集上它会很重要。
    【解决方案3】:

    您可以尝试以下方法。

    [Haystack.index(x) for x in needles if x in Haystack]
    

    如果 x 不在 haystack 中,则不会调用 haystack.index(x) 并且不会抛出错误。

    【讨论】:

    • 实际上不会起作用,因为您总是会获得任何重复元素的第一个索引
    【解决方案4】:

    绝对不是最有效的方法,但您可以这样做:

    result = []
    i=0
    while (i < len(haystack)):
        if (needles.count(haystack[i]) > 0):
            result.append(i)
        i+=1
    

    这将使结果 = [3, 6, 8]

    【讨论】:

      【解决方案5】:

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

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

      enumerate 函数生成一个生成元组的生成器——第一个是索引,第二个是一个值:

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

      只需检查每个值是否在您的针头列表中,如果是则添加索引。

      【讨论】:

        猜你喜欢
        • 2019-10-28
        • 1970-01-01
        • 2018-04-02
        • 1970-01-01
        • 2014-12-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多