You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python统计字符类型时如何让字典返回计数为0的键值对

问题原因

现有代码仅在遍历到对应类型的字符时,才会通过setdefault给字典添加对应键,没有出现的字符类型不会生成对应键,因此返回结果里没有值为0的键值对。

解决方案

在函数初始化字典阶段,提前定义好所有需要统计的字符类型键,默认值设为0,遍历字符时直接对对应键的值累加即可,无需再调用setdefault。

修改后的代码如下:

def count_types(string):
    # 提前预置所有需要统计的字符类型,默认计数为0
    dictionary = {
        "lower": 0,
        "upper": 0,
        "punctuation": 0,
        "space": 0,
        "numeral": 0
    }

    for char in string:
        if 'Z' >= char >= 'A':
            dictionary["upper"] += 1
        elif 'z' >= char >= 'a':
            dictionary["lower"] += 1
        elif char == ' ':
            dictionary["space"] += 1
        elif '9' >= char >= '0':
            dictionary["numeral"] += 1
        else:
            dictionary["punctuation"] += 1
    return dictionary

print(count_types("aabbccc")) 

运行后输出和你期望的完全一致:

{'lower': 7, 'upper': 0, 'punctuation': 0, 'space': 0, 'numeral': 0}

内容的提问来源于stack exchange,提问作者PlumChy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 17:24:01