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

询问Python中isdigit()识别5/5失效原因及判断全满分的实现方法

问题原因

str.isdigit() 方法的判断逻辑为:仅当字符串内所有字符均为阿拉伯数字时返回True。你使用的成绩字符串包含斜杠/字符,不属于数字字符范畴,因此类似5/5的字符串调用isdigit()永远返回False,计数逻辑自然无法正常运行。

实现方案

处理思路为:对每条成绩字符串按/拆分成分数、满分两个部分,转换为整数后判断二者是否相等,所有成绩都满足相等条件的用户即符合要求。

基础实现(兼容原有代码结构)

# dictionary could be larger
dicti = {'John': ['5/5', '50/50', '10/10', '10/10'], 'Test': ['4/5', '20/20']}
liste = []
def f():
    for key, value in dicti.items():
        all_full_score = True
        for i in value:
            # 拆分成绩为得分、满分两部分
            get_score, full_score = i.split('/')
            if int(get_score) != int(full_score):
                all_full_score = False
                # 存在非满分成绩,直接跳出循环无需后续判断
                break
        if all_full_score:
            liste.append(key)
    print(liste)
f()

上述代码运行输出为['John'],符合需求。

鲁棒性增强版本

如果存在成绩格式不规范的场景(比如无斜杠、非数字内容、分母为0等),可增加异常捕获逻辑避免报错:

dicti = {'John': ['5/5', '50/50', '10/10', '10/10'], 'Test': ['4/5', '20/20'], 'Err': ['10//10', 'a/5']}
liste = []
def f():
    for key, value in dicti.items():
        all_full_score = True
        for i in value:
            try:
                get_score, full_score = i.split('/')
                if int(get_score) != int(full_score):
                    all_full_score = False
                    break
            except (ValueError, ZeroDivisionError):
                all_full_score = False
                break
        if all_full_score:
            liste.append(key)
    print(liste)
f()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 15:21:01