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

Python使用智能zip将列表转字典时同键值累加的实现问题

问题根因

你原有代码通过zip(it, it)将列表两两分组后直接转为字典,Python 字典的默认逻辑是:插入重复键时,后出现的键值会直接覆盖已有键值,不会自动做数值累加,因此无法得到你想要的求和结果。

修改方案

方案1:迭代器遍历实现(兼容原有迭代器写法)

def Convert(a):
    it = iter(a)
    res_dct = {}
    for key in it:
        value = next(it)
        # 存在键就累加,不存在就赋初始值
        res_dct[key] = res_dct.get(key, 0) + value
    return res_dct

方案2:按步长遍历实现(逻辑更直观易读)

def Convert(a):
    res_dct = {}
    # 按步长2遍历列表,每次取一组键值
    for i in range(0, len(a), 2):
        key = a[i]
        value = a[i+1]
        res_dct[key] = res_dct.get(key, 0) + value
    return res_dct

效果验证

传入示例列表['apples', 400, 'sweets', 300, 'apples', 750]调用函数,返回结果为{'apples': 1150, 'sweets': 300},符合预期需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 21:36:04