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
相关产品推荐
相关产品推荐

