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

使用dataclass列表遍历匹配输入整数时出现匹配失败问题

问题分析与修复

你的代码有两个核心问题,导致无论输入正确ID还是错误ID,都会输出"no":

  • 比较对象完全错误:你把输入的整数直接和整个dog_details列表做相等判断——一个整数和列表永远不可能相等,所以必然触发print("no")。
  • 循环逻辑混乱:while True内部嵌套了遍历列表的for循环,导致每次输入后会被重复判断多次,完全偏离了需求逻辑。

修复后的代码

from dataclasses import dataclass

@dataclass
class Dog:
    ID: int
    name: str

dog_details = [
    Dog(ID=1, name="Toby"),
    Dog(ID=2, name="Rex"),
    Dog(ID=3, name="Sandy"),
    Dog(ID=4, name="Wanda"),
    Dog(ID=5, name="Toto"),
]

while True:
    identification = int(input("What ID? "))
    match_found = False
    # 遍历每个Dog对象,检查ID匹配情况
    for dog in dog_details:
        if identification == dog.ID:
            match_found = True
            break
    print("Yes" if match_found else "no")

关键修改说明

  • 把输入操作移到for循环外面,避免每次遍历列表都重复要求用户输入。
  • 直接遍历列表中的Dog对象,不用索引间接访问,代码更简洁直观。
  • 对比时用dog.ID(每个对象的ID属性)和输入值比较,而不是错误地和整个列表对比。
  • 用match_found标记是否找到匹配项,遍历结束后统一输出结果,避免多次输出冗余内容。

如果想让代码更简洁,还可以用any()函数简化判断逻辑:

while True:
    identification = int(input("What ID? "))
    print("Yes" if any(dog.ID == identification for dog in dog_details) else "no")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 06:20:30