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

如何在字典中映射列表中子字符串的匹配索引位置

问题描述

给定两个列表:一个字符串列表和一个子字符串列表,代码如下:

list_strings = ['applepearnutapplepear', 'pearappleapplepearnut', 'nutapplepearnutnut']

list_ss = ['ple', 'ear']

需要在字符串列表的所有字符串中搜索每个子字符串,找到所有匹配的起始索引位置,最终整理成如下格式的字典:

{
    "substring1": [index1, index2, ...],
    "substring2": [index1, index2, ...]
}

示例:dict_found = {'ple': [2, 14], ...}

解决方法

通过遍历子字符串与目标字符串,循环查找所有匹配位置并收集索引,即可构建目标字典。

实现代码:

list_strings = ['applepearnutapplepear', 'pearappleapplepearnut', 'nutapplepearnutnut']
list_ss = ['ple', 'ear']

# 初始化结果字典,每个子字符串对应空列表
dict_found = {ss: [] for ss in list_ss}

for substring in list_ss:
    for target_str in list_strings:
        start_pos = 0
        while True:
            # 从start_pos开始查找子字符串
            match_idx = target_str.find(substring, start_pos)
            if match_idx == -1:
                # 找不到匹配,退出当前字符串的查找循环
                break
            dict_found[substring].append(match_idx)
            # 更新起始位置,避免重复匹配重叠内容
            start_pos = match_idx + 1

print(dict_found)

运行代码后输出:

{'ple': [2, 14], 'ear': [4, 16, 3, 13, 6]}

关键说明

  • 使用str.find(sub, start)方法,指定起始位置来逐个查找子字符串的所有出现
  • 每次找到匹配后,将起始位置更新为match_idx + 1,确保不会重复匹配重叠的子串(比如若子串是"aaa",字符串是"aaaa",这样会找到索引0和1两个位置)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 02:28:21