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

Python如何提取3字符子串匹配字典键并生成新字典

解决方案

以下是Python实现代码,直接运行即可得到预期结果:

def get_substr_and_match(dict1, str1):
    # 提取所有长度为3的连续子串
    substr_list = [str1[i:i+3] for i in range(len(str1) - 2)]
    # 匹配字典键生成新字典
    new_dict = {k: dict1[k] for k in substr_list if k in dict1}
    return substr_list, new_dict

# 示例参数
dict1 = {'000': 0, '001': 0, '010': 0, '011': 0, '100': 1, '101': 0, '110': 1, '111': 0}
str1 = '010110100'

substr_result, match_result = get_substr_and_match(dict1, str1)
print("所有3长度子串列表:", substr_result)
print("匹配后新字典:", match_result)
运行结果
所有3长度子串列表: ['010', '101', '011', '110', '101', '010', '100']
匹配后新字典: {'010': 0, '101': 0, '011': 0, '110': 1, '100': 1}
注意事项

因为Python字典的键天然唯一,即使子串重复出现,新字典中也只会保留一个对应键值对,如果需要统计匹配次数,可以把生成新字典的逻辑替换为计数逻辑即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 11:15:03