Z个怎么做请求支援一下

输入一个字符串,输出每个字符以及字符对应的出现次数。
例如输入:abccdef
输出:
a 1
b 1
c 2
d 1
e 1
f 1

  • 方法一、用字符串方法 str.count() 统计
    Python 代码:

1、基本函数


def mycount(s: str) -> str:
    ''' str.count() 方法统计字符出现频次 '''
    counted = [] # 记录已统计字符。
    
    for i in s:

        if i not in counted: # 如果字符没有统计过,统计输出后将字符加入已统计列表。
            print(i, s.count(i))
            counted.append(i)

2、输出格式化


def mycount2(s: str) -> str:
    ''' str.count() 方法统计字符出现频次 '''
    result = []

    for i in s:
        result.append((i, s.count(i)))

    result = list(set(result)) # 集合去重。
    result.sort() # 升序排序。
    result = [f"{i[0]}: {i[-1]}" for i in result] # 列表解析格式化字符计数。
    return '\n'.join(result) # 返回一个字符统计一行的格式化输出结果。

3、函数调用


if __name__ == '__main__':
    input_s = 'abccdef'
    mycount(input_s)
    print(f"\n统计字符串{input_s}字符出现频次:\n{mycount2(input_s)}")

4、代码运行效果截屏图片

img

  • 方法二、用字典记录出现次数。
      字符为 key ,出现次数为值。最后输出字典键值对。

1、 Python 代码


def mycount_dict(s: str) -> str:
    ''' dict 存储字符串统计 '''
    counts = {} # 字符统计存储字典。

    for i in s:
        counts[i] = counts.get(i, 0) + 1 # 统计数据存入字典。

    return '\n'.join([f"{key}: {value}" for key, value in counts.items()])

2、代码运行效果截屏图片

img


  我以前练习笔记“练习:字符串统计(坑:f‘string‘报错)”,可以点击跳转翻阅。