递归计算存储单元总数量时遇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字段的字典,需要遍历提取该字段的值,而非直接操作列表本身。
修正后的递归函数
针对不同数据类型做针对性处理:
- 若为字典:先判断是否是带
quantity的存储单元字典,是则直接返回值;否则遍历所有值递归求和 - 若为列表:遍历列表内每个元素,递归处理每个元素
- 其他无关类型直接忽略
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
相关产品推荐
相关产品推荐

