首页 > 解决方案 > 递归地展平具有低指针和高指针的嵌套整数列表

问题描述

我已经看到一些答案将嵌套的整数列表(第一个代码片段)展平,并将列表作为唯一参数:flatten(lst). 我的任务是做同样的事情,但有两个指数(低 <= 高)表示要考虑的指数范围:flatten(lst, low, high).

带一个参数的工作代码

def flatten(lst):
    if not lst:
        return lst
    if isinstance(lst[0], list):
        return flatten(lst[0]) + flatten(lst[1:])
    return lst[:1] + flatten(lst[1:])

我用打印语句测试了我的代码并且展平过程是正确的,问题是我不确定如何将所有单个值放回列表中以返回它。希望这是有道理的,我不确定还有什么可以尝试的。先感谢您!

我的代码

def flatten(lst, low, high):
    if low > high:
        return lst
    elif isinstance(lst[low], list):
        return flatten(lst[low], 0, len(lst[low]) - 1) + flatten(lst[low + 1:], 0, len(lst[low + 1:]) - 1)
    else:
        return lst[:low] + flatten(lst[low + 1:], 0, len(lst[low + 1:]) - 1)

这就是我用来测试我的代码的东西。

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

标签: pythonlistrecursion

解决方案


您可以按原样使用带有下标赋值的原始函数:

def flatten(lst):
    if not lst:
        return lst
    if isinstance(lst[0], list):
        return flatten(lst[0]) + flatten(lst[1:])
    return lst[:1] + flatten(lst[1:])

L = [[1, 2], 3, [4, [5, 6, [7], 8]]]

L[0:2] = flatten(L[0:2])
print(L)

[1, 2, 3, [4, [5, 6, [7], 8]]]

或者实现一个使用第一个函数的新函数:

def flattenRange(L,low,high):
    L = L.copy()
    L[low:high] = flatten(L[low:high]) # use high+1 if it is inclusive
    return L

甚至是“混蛋”……我的意思是“增强”原作:

def flatten(lst,low=0,high=None):
    if low>0 or high is not None:
        lst = lst.copy()
        lst[low:high] = flatten(lst[low:high]) # use high+1 if it's inclusive
        return lst
    if not lst:
        return lst
    if isinstance(lst[0], list):
        return flatten(lst[0]) + flatten(lst[1:])
    return lst[:1] + flatten(lst[1:])

推荐阅读