如何用Python生成指定层数的嵌套列表?
Python实现指定层数的嵌套列表函数
这里提供几种简单的实现方式,满足生成对应层数嵌套列表的需求:
方法一:循环迭代(直观易懂)
通过循环逐步将当前结果包裹进列表,直到达到指定层数:
def nested_list(how_many_lists): result = 'hi' for _ in range(how_many_lists): result = [result] return result
示例:
nested_list(2)返回[['hi']]nested_list(10)返回10层嵌套的包含'hi'的列表
方法二:递归实现(简洁优雅)
利用递归思想,每次将层数减1,直到层数为0时返回基础字符串:
def nested_list(how_many_lists): if how_many_lists == 0: return 'hi' return [nested_list(how_many_lists - 1)]
递归的边界条件是how_many_lists == 0,此时返回原始字符串,每往上一层就将结果包裹进列表。
方法三:使用reduce函数(一行式写法)
借助functools.reduce函数,用更简洁的方式完成迭代包裹:
from functools import reduce def nested_list(how_many_lists): return reduce(lambda acc, _: [acc], range(how_many_lists), 'hi')
reduce会依次将累积值acc传入lambda表达式,每次将其包裹为列表,初始累积值为'hi',迭代次数由how_many_lists指定。
内容的提问来源于stack exchange,提问作者Normal_cat
相关产品推荐
相关产品推荐

