首页 > 解决方案 > 从列表中查找子列表的索引跨度

问题描述

给定字符串 L 的列表和 L 的子列表 M。我想找到一种有效的方法来从 L 中找到索引跨度 (index_a, index_b),其中 L[index_a: index_b] = M。

例如,

L = ['Clement', 'Joseph', 'Man', '##ey', 'was', 'an', 'American', 'businessman', 'from', 'Boston', 'who', 'was', 'president', 'of', 'a', 'contracting', 'company', 'and', 'a', 'minority', 'owner', 'and', 'treasurer', 'of', 'the', 'Boston', 'Braves', 'baseball', 'team', '.']
M = ['Clement', 'Joseph', 'Man', '##ey']

Expected_result = (0,4) # since L[0:4] = M

L = ['Clement', 'Joseph', 'Man', '##ey', 'was', 'an', 'American', 'businessman', 'from', 'Boston', 'who', 'was', 'president', 'of', 'a', 'contracting', 'company', 'and', 'a', 'minority', 'owner', 'and', 'treasurer', 'of', 'the', 'Boston', 'Braves', 'baseball', 'team', '.']
M = ['Boston']

Expected_result = (9,9) # both (9,9) and (25,25) are correct since L[9]=L[25]=M

标签: pythonlist

解决方案


使用理解,并在返回值时检查长度:

def getIndex(lst1, lst2):
    index1 = next((i for i in range(len(lst1) - len(lst2)) if lst1[i:i + len(lst2)] == lst2), None)
    if index1 is not None: # when sub list doesn't exist in another list
        return (index1, index1) if len(lst2) == 1 else (index1, index1+len(lst2))
    else:
        return None
L1 = ['Clement', 'Joseph', 'Man', '##ey', 'was', 'an', 'American', 'businessman', 'from', 'Boston', 'who', 'was',
     'president', 'of', 'a', 'contracting', 'company', 'and', 'a', 'minority', 'owner', 'and', 'treasurer', 'of', 'the',
     'Boston', 'Braves', 'baseball', 'team', '.']
M1 = ['Clement', 'Joseph', 'Man', '##ey']

L2 = ['Clement', 'Joseph', 'Man', '##ey', 'was', 'an', 'American', 'businessman', 'from', 'Boston', 'who', 'was', 'president', 'of', 'a', 'contracting', 'company', 'and', 'a', 'minority', 'owner', 'and', 'treasurer', 'of', 'the', 'Boston', 'Braves', 'baseball', 'team', '.']
M2 = ['Boston']

print(getIndex(L1, M1))
print(getIndex(L2, M2))

结果:

(0, 4)
(9, 9)

或一行:

def getIndex(lst1, lst2):
    return next(((i, i + (len(lst2) if len(lst2) > 1 else 0)) for i in range(len(lst1) - len(lst2)) if lst1[i:i + len(lst2)] == lst2), None)

推荐阅读