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

时间:2019-04-04 21:26:21

标签: python-3.x list intersection

我有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)],因此它将所有匹配项视为不是列表中的整个列表。

2 个答案:

答案 0 :(得分:1)

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

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的连续切片进行比较。当它们匹配时,它将创建匹配索引的列表。

答案 1 :(得分:1)

您可以使用最大长度为c = a[(b == 1) & (d == 1)] 的{​​{1}},并将collections.deque的项目放入其中以充当滚动窗口。如果队列的内容与l2的内容匹配,则输出当前索引及其前一个索引,直到l1的长度:

l2

这将输出:

l2
相关问题