Python如何按出现顺序统计字符串字符频率并按指定格式输出
Python实现指定格式的字符频率统计
你之前找的全局频率统计方案不符合需求,原因是该方案统计的是整个字符串中所有相同字符的总出现次数,且默认不保留字符的出现顺序。根据你给出的示例,实际需求是统计连续出现的相同字符的数量,同时保留原字符串的空格分隔逻辑,多个连续空格合并为单个分隔符。
实现代码
def count_continuous_chars(s: str) -> str: # 先按空格拆分字符串,自动合并多个连续空格 words = s.split() res = [] for word in words: if not word: continue word_res = [] current_char = word[0] count = 1 # 遍历单词内的字符,统计连续相同字符 for c in word[1:]: if c == current_char: count += 1 else: word_res.append(f"{current_char}{count}") current_char = c count = 1 # 加上最后一组字符的统计结果 word_res.append(f"{current_char}{count}") res.append(''.join(word_res)) # 用单个空格拼接所有单词的处理结果 return ' '.join(res)
测试验证
运行以下测试用例可匹配你给出的预期输出:
count_continuous_chars("aaaa")返回a4count_continuous_chars("abb")返回a1b2count_continuous_chars("abbb cc a")返回a1b3 c2 a1count_continuous_chars("bbbaaacddddee")返回b3a3c1d4e2count_continuous_chars("a b")返回a1 b1
内容的提问来源于stack exchange,提问作者Wicaledon
相关产品推荐
相关产品推荐

