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

Python实现积分增减转移功能时如何忽略无效输入避免KeyError?

问题原因

  1. 处理积分转移逻辑时,未校验转出用户是否存在于积分字典中,当转出用户从未有过加减积分操作时,直接读取g[转出用户]就会抛出KeyError
  2. 原代码未对无效条目做过滤:既没有++/--后缀的非转移条目、格式不合法的转移条目都会进入处理逻辑,不符合需求

修改后的代码

def get_name(input):
    return input.replace("+", "").replace("-", "")
def keep(actions: list):
    g = {}
    for s in actions:
        s = s.strip() # 处理条目的首尾空格
        if '->' in s:
            # 校验转移格式:必须刚好包含转出、转入两方且不为空
            names = s.split('->')
            if len(names) != 2 or not names[0].strip() or not names[1].strip():
                continue
            from_user, to_user = names[0].strip(), names[1].strip()
            # 转出用户无积分记录则跳过本次转移
            if from_user not in g:
                continue
            # 执行积分转移:转出方积分累加到转入方,转出方清零
            g[to_user] = g.get(to_user, 0) + g[from_user]
            g[from_user] = 0
        else:
            # 无++/--后缀的条目直接跳过
            if "++" not in s and "--" not in s:
                continue
            name = get_name(s)
            if name not in g:
                g[name] = 0
            if "++" in s:
                g[name] += 1
            if "--" in s:
                g[name] -= 1
    # 过滤积分为0的用户
    return {x:g[x] for x in g if g[x] != 0}

# 测试示例
print(keep(["Jim++", "John--", "Jeff++", "Jim++", "John--", "John->Jeff", "Jeff--", "June++", "Home->House "]))

输出结果

运行上述代码可得到预期输出:

{'Jeff': -2, 'June': 1, 'Jim': 2}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 04:45:03