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

如何检查列表元素是否包含另一列表元素的子串并拼接结果

问题描述

需求说明

遍历list1中的每个元素,检查该元素是否作为子串存在于list2的元素中;若存在,则将list2中所有包含该子串的字符串拼接为一个新字符串,添加到list3中。

输入示例

list1 = ["2044","1222"]
list2 = ["I am Raman 2044","I am Raman 2044","I am Raman 2044","I am Rohan 1222","I am Rohan 1222"]

注:原输入中的"I am Raman 2044"x属于输入笔误,已修正为正常字符串格式

输出示例

list3 = ["I am Raman 2044I am Raman 2044I am Raman 2044","I am Rohan 1222I am Rohan 1222"]

实现代码(Python)

list1 = ["2044","1222"]
list2 = ["I am Raman 2044","I am Raman 2044","I am Raman 2044","I am Rohan 1222","I am Rohan 1222"]
list3 = []

for keyword in list1:
    # 筛选list2中包含当前关键词的所有字符串
    matched_items = [item for item in list2 if keyword in item]
    # 拼接后加入list3
    list3.append(''.join(matched_items))

print(list3)

内容的提问来源于stack exchange,提问作者Raman

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 11:45:29