You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何扩展代码以适配任意currentLayer层级值?

解决方案:用递归适配任意层级的嵌套列表

要处理任意currentLayer值的嵌套列表,递归是最直观的方案——因为嵌套结构本身就符合递归的“重复子问题”特性。

原地修改版本(和你给出的示例逻辑一致)

def process_layered_list(currentList, currentLayer, someFunction):
    if currentLayer == 1:
        # 到达目标层级,遍历每个元素应用函数
        for i in range(len(currentList)):
            currentList[i] = someFunction(currentList[i])
    else:
        # 未到达目标层级,递归处理每个子列表,层级减1
        for sub_list in currentList:
            process_layered_list(sub_list, currentLayer - 1, someFunction)
    return currentList

非原地修改版本(返回新列表,不改动原数据)

如果不想修改原列表,可以用列表推导式实现更简洁的写法:

def process_layered_list(currentList, currentLayer, someFunction):
    if currentLayer == 1:
        return [someFunction(item) for item in currentList]
    else:
        return [process_layered_list(sub, currentLayer - 1, someFunction) for sub in currentList]

逻辑说明

  • 当currentLayer等于1时,直接遍历当前列表的所有元素,对每个元素调用someFunction;
  • 当currentLayer大于1时,遍历当前列表中的每个子列表,递归调用自身并将层级减1,直到递归到目标层级。

搜索关键词参考

如果以后遇到类似问题,可以搜这些关键词:

  • Python 递归遍历嵌套列表
  • Python 多层嵌套列表处理
  • Nested list iteration Python

内容的提问来源于stack exchange,提问作者Aiden Boudreau

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 22:32:14