如何使用 Python 查找两个列表交集的索引?

How to find indices of two lists intersection using Python?

我有 2 个列表:

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

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

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

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

returns [(1, 0), (3, 0), (4, 1), (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 的连续切片进行比较。当它们匹配时,它会创建匹配索引列表。

您可以使用最大长度为 l2collections.deque 并将 l1 的项目放入其中以充当滚动 window。如果队列的内容与 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]