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

Python如何对两列表做grep匹配,返回搜索词与匹配项键值对

双列表子串匹配实现(返回命中项-搜索词映射)

原有代码仅收集了list2中的命中元素,未关联对应命中它的list1搜索词,因此无法输出要求的键值对结构。调整实现逻辑,在遍历匹配时同步记录映射关系即可。

基础实现(单个命中项对应单个搜索词)

匹配规则:以list1元素为搜索词,检索list2中包含对应搜索词的元素,最终返回字典,key为list2中的命中项,value为命中该元素的搜索词。若单个list2元素命中多个list1搜索词,按list1遍历顺序,后命中的搜索词会覆盖之前的记录。

def find_in_list(list1, list2):
    matches = {}
    for search_term in list1:
        for item in list2:
            if search_term in item:
                matches[item] = search_term
    return matches

# 测试示例
list1 = ["dog", "cat", "mouse"]
list2 = ["bigdog", "blackcat", "horse"]
print(find_in_list(list1, list2))

运行输出:
{'bigdog': 'dog', 'blackcat': 'cat'},完全符合预期格式。

扩展实现(支持单个命中项对应多个搜索词)

如果需要保留单个list2元素命中的所有搜索词,可以将字典value调整为列表结构存储所有匹配的搜索词:

def find_in_list_multi(list1, list2):
    matches = {}
    for search_term in list1:
        for item in list2:
            if search_term in item:
                # 首次命中时初始化空列表
                if item not in matches:
                    matches[item] = []
                matches[item].append(search_term)
    return matches

内容的提问来源于stack exchange,提问作者b3n-j4m1n

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 11:57:21