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

遍历字典时出现str与int类型错误,如何修复Python代码?

修复代码的方案

错误原因

  1. 遍历字典时直接写for value in courses,实际拿到的是字典的键(字符串类型,比如"mon"),不是对应的座位数值,导致和整数比较时触发类型错误。
  2. 代码中elif value >= 20 and key<=24里的key变量未定义,属于笔误。

修复方案

方案1:仅遍历座位数(不需要关联星期)

将遍历对象改为courses.values(),直接获取字典的数值,同时修正未定义的变量:

courses = {"mon":20,
       "tues":25,
       "wed":13,
       "thurs":5,
       "fri":25}
for seat_count in courses.values():
    if seat_count == 25:
        print("course is full")
    elif 20 <= seat_count <= 24:
        print("course is almost full")
    elif seat_count < 20:
        print("plenty of seats left")

方案2:同时获取星期和座位数(推荐,保留关联信息)

用courses.items()遍历键值对,同时拿到星期和对应的座位数,还能输出更明确的状态:

courses = {"mon":20,
       "tues":25,
       "wed":13,
       "thurs":5,
       "fri":25}
for day, seat_count in courses.items():
    if seat_count == 25:
        print(f"{day}: course is full")
    elif 20 <= seat_count <= 24:
        print(f"{day}: course is almost full")
    elif seat_count < 20:
        print(f"{day}: plenty of seats left")

关键说明

  • courses.values()返回字典所有值的迭代器,每个元素都是整数,解决了类型不匹配的问题。
  • courses.items()返回(键, 值)元组,能同时获取星期和座位数,适合需要关联信息的场景。
  • 把原代码中冗余的value >=20 and key<=24简化为20 <= seat_count <=24,逻辑一致且更易读。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 23:10:30