You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 08:58:13