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

如何向内嵌层级最深的列表添加后续数值元素?

如何向内嵌层级最深的列表添加后续数值元素?

需求说明:遍历嵌套列表,找到所有层级最深的子列表,为每个这样的子列表追加一个元素——该子列表最后一个元素的后续整数(例如子列表最后一个元素是7则追加8,是3则追加4)。

示例1

输入:

list_in = [2, 3, [4, 5, [6, 7], 6], 2, [5, 6]]

输出:

list_out = [2, 3, [4, 5, [6, 7, 8], 6], 2, [5, 6]]

这里最深的子列表是[6,7],追加了8。

示例2

输入:

list_in = [2, [4], [3]]

输出:

list_out = [2, [4, 5], [3, 4]]

这里有两个层级相同的最深子列表[4]和[3],分别追加了5和4。


实现方案(Python)

通过两次递归遍历实现:第一次确定最大嵌套深度,第二次找到对应深度的子列表并修改。

代码实现

def find_max_depth(lst, current_depth=0):
    max_depth = current_depth
    for item in lst:
        if isinstance(item, list):
            depth = find_max_depth(item, current_depth + 1)
            if depth > max_depth:
                max_depth = depth
    return max_depth

def add_to_deepest_lists(lst, target_depth, current_depth=0):
    for i, item in enumerate(lst):
        if isinstance(item, list):
            if current_depth + 1 == target_depth:
                # 找到最深子列表,追加最后一个元素+1
                lst[i].append(item[-1] + 1)
            else:
                # 继续递归处理更深的子列表
                add_to_deepest_lists(item, target_depth, current_depth + 1)
    return lst

# 使用示例
list_in1 = [2, 3, [4, 5, [6, 7], 6], 2, [5, 6]]
max_depth1 = find_max_depth(list_in1)
list_out1 = add_to_deepest_lists(list_in1, max_depth1)
print(list_out1)  # 输出: [2, 3, [4, 5, [6, 7, 8], 6], 2, [5, 6]]

list_in2 = [2, [4], [3]]
max_depth2 = find_max_depth(list_in2)
list_out2 = add_to_deepest_lists(list_in2, max_depth2)
print(list_out2)  # 输出: [2, [4, 5], [3, 4]]

代码解释

  1. find_max_depth函数:递归遍历列表,计算每个子列表的嵌套深度,返回整个结构中的最大深度。根列表的深度为0,直接子列表深度为1,以此类推。
  2. add_to_deepest_lists函数:再次递归遍历列表,当遇到子列表的深度等于最大深度时,给该子列表追加最后一个元素+1的数值;如果子列表深度不足,则继续递归处理其内部元素。
  3. 该方案会处理所有层级等于最大深度的子列表,满足多个最深子列表的修改需求。

内容的提问来源于stack exchange,提问作者Malum Phobos

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 21:31:11