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

如何简化预算分类的多分支if-elif-else?字典方案为何失效?

简化预算分类匹配并修复字典方案问题

问题分析

你尝试的字典方案失败的核心原因是循环逻辑错误:每次循环只检查第一个分类的关键词,一旦不匹配就直接返回'other',完全没机会遍历后续分类。比如输入'taxi'时,第一个分类是'shopping','taxi'不在其列表中,代码直接执行return 'other'终止流程,根本没检查到'transport & car'分类。

修复与简化方案

方案1:修正遍历逻辑(保留原字典结构)

调整循环逻辑,确保所有分类都被检查,找到匹配项后终止循环,默认值设为'other':

desc = input("what have you spent on? ")
cat_dict = {
    'shopping': ['cloth', 'watch', 'shoes', 'shirt', 'pants','skirt', 'dress', 'hat', 'H&M', 'C&A', 'Zalando'],
    'food & grocery': ['lidl', 'kaufland', 'food', 'veggies', 'meat', 'eggs', 'milk'],
    'bar & restaurants':['meals', 'drink','coffee','bakery', 'cake'],
    'transport & car':['bus', 'flight','train','transport','taxi'],
    'rent':['rent'],
    'cash':['withdraw', 'cash'],
    'ATM':['ATM'],
    'travel':['accommodation','room','hostel','hotel'],
    'household & utilities':['internet'],
    'healthcare & drug':['rossmann', 'dm'],
    'giving' :['donation']
} 

category = 'other'  # 预设默认分类
for key, val in cat_dict.items():
    if desc in val:
        category = key
        break  # 找到匹配项立即终止循环
print(category)

关键改进:

  • 提前设置默认分类'other',避免中途错误返回
  • 遍历所有分类后才会确认无匹配项,确保逻辑完整

方案2:反转字典(更高效的查找方式)

如果关键词数量较多,遍历字典的效率较低,可以将字典反转,让每个关键词直接映射到对应分类,实现O(1)时间复杂度的查找:

desc = input("what have you spent on? ").lower()  # 统一转小写,兼容大小写输入
# 反转字典:关键词 -> 分类
keyword_to_cat = {
    **{item: 'shopping' for item in ['cloth', 'watch', 'shoes', 'shirt', 'pants','skirt', 'dress', 'hat', 'h&m', 'c&a', 'zalando']},
    **{item: 'food & grocery' for item in ['lidl', 'kaufland', 'food', 'veggies', 'meat', 'eggs', 'milk']},
    **{item: 'bar & restaurants' for item in ['meals', 'drink','coffee','bakery', 'cake']},
    **{item: 'transport & car' for item in ['bus', 'flight','train','transport','taxi']},
    **{item: 'rent' for item in ['rent']},
    **{item: 'cash' for item in ['withdraw', 'cash']},
    **{item: 'ATM' for item in ['atm']},
    **{item: 'travel' for item in ['accommodation','room','hostel','hotel']},
    **{item: 'household & utilities' for item in ['internet']},
    **{item: 'healthcare & drug' for item in ['rossmann', 'dm']},
    **{item: 'giving' for item in ['donation']}
}

# 用get方法直接获取,无匹配则返回默认值'other'
category = keyword_to_cat.get(desc, 'other')
print(category)

优势:

  • 查找速度更快,适合关键词数量多的场景
  • 代码更简洁,核心查找逻辑仅需一行

额外优化建议

  • 加入大小写转换:将输入和关键词统一转小写,避免'Taxi'或'TAXI'无法匹配的问题
  • 支持模糊匹配:如果需要识别包含关键词的描述(比如'taxi ride'),可以将匹配逻辑改为if any(keyword in desc for keyword in val)(方案1适用)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 09:53:19