【问题标题】:How to find indices of two lists intersection using Python?如何使用 Python 查找两个列表交集的索引?
【发布时间】:2019-04-04 21:26:20
【问题描述】:

我有 2 个列表:

l1 = ['oak', 'tree', ',', 'tree', 'preservation', 'order', 'to',
 'be', 'crowned', 'and', 'cleared', 'of', 'deadwood']
l2 =  ['tree', 'preservation', 'order']

我需要找到这些交集的索引。结果应该只是[3,4,5] 的列表。

问题是我发现的算法返回错误的值。例如:

def find_matching_indices(a, b):
    for i, x in enumerate(a):
        for j, y in enumerate(b):
            if x == y:
                yield i, j

返回[(1, 0), (3, 0), (4, 1), (5, 2)],因此它认为所有匹配项不是列表中的整个列表。

【问题讨论】:

标签: python-3.x list intersection


【解决方案1】:

您可以使用最大长度为l2collections.deque 并将l1 的项目排入其中以充当滚动窗口。如果队列的内容与l2的内容匹配,则输出当前索引加上它之前的索引,直到l2的长度:

from collections import deque
q = deque(maxlen=len(l2))
for i, s in enumerate(l1):
    q.append(s)
    if list(q) == l2:
        print(list(range(i - len(l2) + 1, i + 1)))

这个输出:

[3, 4, 5]

【讨论】:

  • 谢谢。测试了许多解决方案,我认为这是最佳方法。
【解决方案2】:

这不是最有效的算法,但你可以这样做:

l1 = ['oak', 'tree', ',', 'tree', 'preservation', 'order', 'to',
 'be', 'crowned', 'and', 'cleared', 'of', 'deadwood']
l2 =  ['tree', 'preservation', 'order']

def intersection(l1, l2):            
    for i in range(len(l1)-len(l2)+1):
        if l1[i:i+len(l2)] == l2:
            return [j for j in range(i, i+len(l2))]

print(intersection(l1, l2))
# [3, 4, 5]

它只是将简短的l2 列表与l1 的连续切片进行比较。当它们匹配时,它会创建匹配索引列表。

【讨论】:

    猜你喜欢
    • 2012-09-16
    • 2021-09-17
    • 2014-12-07
    • 2010-10-13
    • 2013-10-12
    • 2021-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多