python - 从列表中查找子列表的索引跨度
问题描述
给定字符串 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
解决方案
使用理解,并在返回值时检查长度:
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)
推荐阅读
- javascript - 出现错误 Module not found: Error: Can't resolve '../components/***' when webpack build, 我该如何解决这个问题?
- excel - 如何在没有代码的情况下将我为整列记录的宏运行到另一列?
- python - 如何使用 Kubernetes Python API 获取集群信息?
- replace - sas 从数据集中删除特定值并替换为缺失
- php - Twilio 传真 - 如何在 PHP 中管理 Wordpress 中的状态响应?
- python - 如何将 PATH 变量添加到 Linux 应用服务计划
- javascript - 如何在反应中使用全局变量?
- signalr-hub - 从域服务和应用层访问 SignalR
- tslint - 用于对象函数调用的 tslint ter-indent
- python-3.x - 如何将每行列值与后续行列值相加并使用新旧行创建新数据框