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

基于low、high指针递归展平指定索引范围的整数嵌套列表实现问题

嵌套列表指定区间展平方案

现有代码问题

  • 终止条件错误:low > high分支返回原列表lst而非空列表,会引入多余的非目标区间内容
  • 区间处理逻辑错误:处理完lst[low]后直接对列表切片lst[low+1:]并从索引0开始递归,丢失了外层传入的high参数约束,无法实现仅处理指定[low, high]区间的需求
  • 结果拼接逻辑错误:lst[:low]会重复携带low索引前的元素,导致最终结果出现冗余内容

修正后代码

def flatten(lst, low, high):
    # 区间无元素时返回空列表
    if low > high:
        return []
    current = lst[low]
    if isinstance(current, list):
        # 展平当前位置的嵌套列表
        current_res = flatten(current, 0, len(current) - 1)
    else:
        # 普通整数包装为单元素列表
        current_res = [current]
    # 拼接当前处理结果 + 后续区间的展平结果
    return current_res + flatten(lst, low + 1, high)

测试验证

运行测试用例:

print(flatten([[1, 2], 3, [4, [5, 6, [7], 8]]], 0, 2))

输出结果为:[1, 2, 3, 4, 5, 6, 7, 8],符合预期。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 14:09:03