以下是一个示例代码,用于遍历嵌套结构并返回每个结构中值的总和。
def sum_nested_structure(nested_structure):
total_sum = 0
# 递归函数用于遍历嵌套结构
def recursive_sum(structure):
nonlocal total_sum
if isinstance(structure, (int, float)):
total_sum += structure
elif isinstance(structure, (list, tuple)):
for item in structure:
recursive_sum(item)
elif isinstance(structure, dict):
for key, value in structure.items():
recursive_sum(value)
recursive_sum(nested_structure)
return total_sum
# 示例嵌套结构
nested_structure = [
1,
2,
[3, 4, [5, 6]],
{'a': 7, 'b': [8, 9]}
]
total_sum = sum_nested_structure(nested_structure)
print(total_sum) # 输出:45
在这个示例中,我们定义了一个名为sum_nested_structure
的函数。该函数使用了一个递归函数recursive_sum
来遍历嵌套结构并计算总和。
recursive_sum
函数接受一个参数structure
,表示当前要处理的结构。在每个递归步骤中,我们使用isinstance
函数来判断当前结构的类型。
structure
是整数或浮点数,则将其值添加到total_sum
中。structure
是列表或元组,则逐个遍历其中的元素,并对每个元素递归调用recursive_sum
函数。structure
是字典,则遍历其中的键值对,并对每个值递归调用recursive_sum
函数。最后,我们在主函数sum_nested_structure
中调用recursive_sum
函数,并返回最终的总和total_sum
。
在示例中,我们使用了一个包含嵌套层级的列表作为输入,并打印最终的总和。输出结果是45,表示嵌套结构中所有值的总和为45。
上一篇:遍历嵌套对象以形成字符串
下一篇:遍历嵌套结构中的值