如何编写Python函数查找字符串重复字符并返回对应位置字典
Python实现查找非空格重复字符及对应位置的函数
实现思路
- 遍历输入字符串的同时记录每个字符的索引
- 过滤排除空格字符
- 临时存储所有非空格字符的出现位置列表
- 最终仅保留出现次数≥2的字符条目,返回结果字典
完整代码
def find_duplicate_chars(input_str: str) -> dict: # 存储所有非空格字符的位置索引 char_position_map = {} for index, char in enumerate(input_str): # 跳过空格字符 if char == " ": continue # 初始化字符的位置列表 if char not in char_position_map: char_position_map[char] = [] char_position_map[char].append(index) # 过滤得到仅出现过至少2次的重复字符 return { char: positions for char, positions in char_position_map.items() if len(positions) >= 2 }
测试示例
调用示例:
test_str = "hello world 121" print(find_duplicate_chars(test_str))
输出结果:
{'l': [2, 3, 9], 'o': [4, 7], '1': [12, 14]}
可选调整项
- 如果需要大小写不敏感识别,可在跳过空格的判断后新增一行
char = char.lower() - 如果需要返回从1开始计数的位置,可将存入列表的
index替换为index + 1
内容的提问来源于stack exchange,提问作者allenthemlgpro 034
相关产品推荐
相关产品推荐

