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

递归计算存储单元总数量时遇TypeError错误求助

递归计算存储单元总数量的问题解决

问题背景

需要编写递归函数,计算Storage字典中马德里、巴塞罗那、塞维利亚所有存储单元的总数量。原始数据结构如下:

Storage = {
    "Madrid": [
        {"name": "pencil", "quantity": 5},
        {"name": "cam", "quantity": 11},
        {"name": "powder", "quantity": 51}
    ],
    "Barcelona": {
        "Branch 1": [
            {"name": "pencil", "quantity": 11},
            {"name": "cam", "quantity": 25}
        ],
        "Branch 2": [
            {"name": "pencil", "quantity": 17},
            {"name": "cam", "quantity": 9}
        ]
    },
    "Seville": {
        "Branch 1": {
            "Sub Branch 1": {
                "Sub sub Branch 1": [
                    {"name": "powder", "quantity": 11}
                ]
            }
        },
        "Branch 2": [
            {"name": "pencil", "quantity": 4}
        ]
    }
}

用户编写的递归函数及运行报错:

def recursive_sum(n):
    current_sum = 0
    for key in n:
        if not isinstance(n[key], dict):
            if not isinstance(n[key], str):
                current_sum = current_sum + n[key]
        else:
            current_sum = current_sum + recursive_sum(n[key])
    return current_sum

print(recursive_sum(Storage))

报错信息:

Traceback (most recent call last):
  File "/Users/user/Desktop/pythonProject/main.py", line 85, in <module>
    print(recursive_sum(Storage))
  File "/Users/user/Desktop/pythonProject/main.py", line 79, in recursive_sum
    current_sum = current_sum + n[key]
TypeError: unsupported operand type(s) for +: 'int' and 'list'

错误原因

代码未正确处理列表类型元素:遇到Madrid这类对应列表的键时,直接尝试将列表与整数相加,触发类型错误。同时,列表内是包含quantity字段的字典,需要遍历提取该字段的值,而非直接操作列表本身。

修正后的递归函数

针对不同数据类型做针对性处理:

  1. 若为字典:先判断是否是带quantity的存储单元字典,是则直接返回值;否则遍历所有值递归求和
  2. 若为列表:遍历列表内每个元素,递归处理每个元素
  3. 其他无关类型直接忽略
def recursive_sum(item):
    total = 0
    if isinstance(item, dict):
        # 优先判断是否是存储单元字典
        if "quantity" in item:
            return item["quantity"]
        # 嵌套字典则遍历所有值递归计算
        for value in item.values():
            total += recursive_sum(value)
    elif isinstance(item, list):
        # 遍历列表内每个元素递归计算
        for elem in item:
            total += recursive_sum(elem)
    return total

print(recursive_sum(Storage))  # 输出:144

运行该函数可得到正确总数量:5+11+51+11+25+17+9+11+4 = 144


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 03:25:29