我有一个仓库字典(如下所示),我需要得到'吨'的总和。值可以在字典的不同深度。
warehouses = {
"Warehouse Lisboa": [
{ "name": "apples", "tons": 4},
{ "name": "oranges", "tons": 10},
{ "name": "lemons", "tons": 50}
],
"Warehouse Cascais": {
"Branch 1": [
{ "name": "apples", "tons": 10},
{ "name": "oranges", "tons": 24}
],
"Branch 2": [
{ "name": "apples", "tons": 16},
{ "name": "oranges", "tons": 8}
]
},
"Warehouse Oeiras": {
"Branch 1": {
"Sub Branch 1":{
"Sub sub Branch 1": [
{ "name": "lemons", "tons": 10}
]
}
},
"Branch 2": [
{ "name": "apples", "tons": 3}
]
}
}
我尝试了以下操作,但它返回TypeError:不支持的操作数类型+:'int'和'list':
def stock_fruits(warehouses):
return sum(warehouses.values())
我如何得到字典中所有"吨"值的总和?
考虑使用深度优先搜索方法:
from typing import Union
def stock_fruits(curr: Union[dict, list]) -> int:
if isinstance(curr, dict):
return sum(stock_fruits(value) for value in curr.values())
return sum(entry["tons"] for entry in curr)
warehouses = {
"Warehouse Lisboa": [
{"name": "apples", "tons": 4},
{"name": "oranges", "tons": 10},
{"name": "lemons", "tons": 50}
],
"Warehouse Cascais": {
"Branch 1": [
{"name": "apples", "tons": 10},
{"name": "oranges", "tons": 24}
],
"Branch 2": [
{"name": "apples", "tons": 16},
{"name": "oranges", "tons": 8}
]
},
"Warehouse Oeiras": {
"Branch 1": {
"Sub Branch 1": {
"Sub sub Branch 1": [
{"name": "lemons", "tons": 10}
]
}
},
"Branch 2": [
{"name": "apples", "tons": 3}
]
}
}
print(f"{stock_fruits(warehouses) = }")
输出:
stock_fruits(warehouses) = 135
您可以使用这个函数来计算总和:
def stock_fruits(warehouses):
fruit_sum = 0
queue = deque(list(warehouses.values()))
while queue:
node = queue.popleft()
if isinstance(node, List):
fruit_sum += sum([item.get('tons', 0) for item in node])
else:
queue.extend(list(node.values()))
return fruit_sum