Python学习笔记:统计字符串字符数量

一、需求

统计传入的字符串,各个字符的出现次数,返回一个 dict 结果。

二、实操

1.方法1:迭代计算

# 方法一:迭代计算
def char_count(strings: str):
    result = {}
    strings = strings.lower()
    for i in strings:
        result[i] = result.get(i, 0) + 1 # 不存在时返回0
    return result

char_count('abcABCDDDD')
# {'a': 2, 'b': 2, 'c': 2, 'd': 4}

方法2:内置模块 collections.Counter

# 方法二:内置模块
from collections import Counter
def char_count2(strings: str):
    strings = strings.lower()
    result = Counter(strings)
    return {**result} # 解包

char_count2('abcABCDDDDd')
# {'a': 2, 'b': 2, 'c': 2, 'd': 5}

参考链接:Python 统计字符串中各字符的数量

posted @ 2022-05-18 00:31  Hider1214  阅读(698)  评论(0编辑  收藏  举报