简体   繁体   English

用低指针和高指针递归地展平嵌套的整数列表

[英]Recursively flatten a nested list of integers with low and high pointers

I have seen a few answers that flattened a nested list of integers (first snippet of code) with the list as the only parameter: flatten(lst) .我已经看到一些答案将嵌套的整数列表(第一个代码片段) flatten(lst) ,并将列表作为唯一参数: flatten(lst) My assignment is to do the same but with two indices (low <= high) that indicates the range of indices to be considered: flatten(lst, low, high) .我的任务是做同样的事情,但有两个指数(低 <= 高)表示要考虑的指数范围: flatten(lst, low, high)

Working code with one parameter带一个参数的工作代码

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:])

I tested my code with print statements and the flattening process is correct, the problem is I'm not sure how to put all the individual values back into the list to return it.我用打印语句测试了我的代码,并且展平过程是正确的,问题是我不确定如何将所有单个值放回列表中以返回它。 Hopefully this makes sense, I'm not sure what else to try.希望这是有道理的,我不知道还有什么可以尝试的。 Thank you in advance!先感谢您!

My code我的代码

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)

This is what I'm using to test my code.这是我用来测试我的代码的内容。

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

You could have used the original function as-is with subscript assignment:您可以按原样使用带有下标赋值的原始函数:

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]]]

Or implement a new function that uses the first one:或者实现一个使用第一个函数的新函数:

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

Or even 'bastardize', ... I mean 'enhance' the original:甚至“混蛋”,......我的意思是“增强”原版:

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:])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM