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

如何在Python中正确遍历字典并实现单复数语法适配?

解决字典遍历与单复数语法适配问题

修正后的代码

favorite_foods = {'bill': 'cake', 'alex': 'patacones'}

for name, food in favorite_foods.items():
    print(f"I don't agree with your favorite food {name.title()}.")
    # 根据食物名称结尾判断单复数,选择对应be动词
    if food.endswith('s'):
        print(f"{food.title()} are delicious, but not that good!")
    else:
        print(f"{food.title()} is delicious, but not that good!")

问题分析与修复说明

  • 字典遍历逻辑错误:原代码外层遍历用户名字,内层又循环遍历所有食物值,导致每个用户都输出全部食物。改用favorite_foods.items()可以同时获取每个用户的名字和对应的专属食物,实现一一对应输出。
  • 单复数判断语法错误:原代码中if food in (favorite_foods.values() endswith(s)完全不符合Python语法,正确做法是直接对当前食物字符串调用endswith('s')方法,判断是否以's'结尾来切换is/are。
  • 拼写错误修正:原代码中delicous是拼写错误,修正为delicious。

验证输出

运行修正后的代码,会得到你期望的结果:

I don't agree with your favorite food Bill.
Cake is delicious, but not that good!
I don't agree with your favorite food Alex.
Patacones are delicious, but not that good!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 16:20:25