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

Python的gnames函数如何过滤返回字典中值为0的键值对

你只需修改gnames()函数的返回逻辑,用字典推导式过滤掉所有值为0的键值对即可,无需改动原有业务逻辑。

修改点

将原函数最后一行的return output替换为以下过滤逻辑:

return {name: count for name, count in output.items() if count != 0}

修改后完整代码

def get_name(string):
    return string.replace("+", "").replace("-", "")

def gnames(input_list: list):
    output = {}
    for entry in input_list:
        if '->' in entry:
            names = entry.split('->')
            output[names[1]] = output[names[0]]
            output[names[0]] = 0
        else:
            name = get_name(entry)
            if name not in output:
                output[name] = 0
            if "++" in entry:
                output[name] += 1
            if "--" in entry:
                output[name] -= 1
    # 最终返回前过滤值为0的条目
    return {name: count for name, count in output.items() if count != 0}

print(gnames(["Jim--", "John--", "Jordan--", "Jim++", "John--", "Jeff--", "June++", "June->Jim"]))

运行结果

执行后输出和预期完全一致:

{'Jim': 1, 'John': -2, 'Jordan': -1, 'Jeff': -1}

补充说明:过滤逻辑放在所有计数、转移操作完成之后执行,不会影响原有业务逻辑的计算结果,只会在最终返回时剔除值为0的条目。

内容的提问来源于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 03:27:03