python 递归 多层字典_消除递归

python 递归 多层字典_消除递归在 Python 中 多重递归通常意味着一个函数在其定义中调用自身 并且这种调用可能不止一次 以下是一些使用递归处理多重列表的例子 例子 1 将多重列表扁平化 pythondef norm list ori list new list for item in ori list if isinstance item list norm list item new list

在Python中,多重递归通常意味着一个函数在其定义中调用自身,并且这种调用可能不止一次。以下是一些使用递归处理多重列表的例子:

例子1:将多重列表扁平化

 def norm_list(ori_list, new_list): for item in ori_list: if isinstance(item, list): norm_list(item, new_list) else: new_list.append(item) return new_list all = [[[1, 2], [3, 4]], [[2, 3], [4, 5]]] new_list = [] new_list = norm_list(all, new_list) print(new_list) 输出: [1, 2, 3, 4, 2, 3, 4, 5] 

例子2:递归遍历双重字典

 def traverse_double_dict(d, depth=1): for k, v in d.items(): if depth == 1: yield k, v else: yield from traverse_double_dict(v, depth - 1) _dict = {'A': {'A1': [1, 2], 'A2': [3, 4]}, 'B': {'B1': [21, 22], 'B2': [23, 24]}} for k, v, x in traverse_double_dict(_dict, 2): print(k, v, x) 

例子3:递归打印多重列表

 def print_li(li): for x in li: if isinstance(x, list): print_li(x) else: print(x) li = [1, [[2, ], , 5], 6, 7, , 9, 10] print_li(li) 

例子4:递归函数返回多个值

 def fibonacci(n): if n <= 1: return (n, 0) else: a, b = fibonacci(n - 1) return (a + b, a) print(fibonacci(5)) 输出: (5, 3) 

这些例子展示了如何使用递归函数处理嵌套的数据结构。每个例子中的递归函数都会检查输入数据是否包含列表,如果是,则递归调用自身;如果不是,则处理当前数据并返回结果。

如果你需要处理更深层次的嵌套结构,可以继续增加递归深度。递归是一种强大的编程技巧,可以简化对复杂数据结构的处理

编程小号
上一篇 2025-05-31 22:07
下一篇 2025-06-06 16:14

相关推荐

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://sigusoft.com/bj/27900.html