Python实现:匹配列表子串并返回元素与子串的元组列表
解决方法
可以用嵌套的列表推导式实现需求,同时遍历ls2的每个元素和ls1的每个子串,检查子串是否为当前ls2元素的子串,满足条件就生成对应的元组:
ls1 = ['apple','banana','pear'] ls2 = ['strawberry is not here', 'blueberry is over there', 'the pear tree is not ready yet', 'we have lots of pear trees', 'apples are yummy'] result = [(s2, s1) for s2 in ls2 for s1 in ls1 if s1 in s2] print(result)
运行代码后,输出结果与预期一致:
[('the pear tree is not ready yet', 'pear'), ('we have lots of pear trees', 'pear'), ('apples are yummy', 'apple')]
逻辑说明
- 外层遍历
ls2中的每个元素s2,内层遍历ls1中的每个子串s1 - 通过
if s1 in s2判断s1是否是s2的子串 - 满足条件时,将
s2和s1组成元组加入结果列表
如果存在单个s2匹配多个s1的情况(比如s2为"apple and pear"),这段代码会生成对应的多个元组,完全符合子串匹配的逻辑。
内容的提问来源于stack exchange,提问作者frank
相关产品推荐
相关产品推荐

