可能重复:
Flatten (an irregular) list of lists in Python
我无法使用python递归地展平列表。我见过许多需要列表理解的方法和需要导入的各种方法,但是我正在寻找一种非常基本的方法来递归地展平一个不使用任何for循环的不同深度的列表。
我做了一系列的测试,但是有两个我不能通过

flatten([[[[]]], [], [[]], [[], []]]) # empty multidimensional list
flatten([[1], [2, 3], [4, [5, [6, [7, [8]]]]]]) # multiple nested list

我的代码
def flatten(test_list):
    #define base case to exit recursive method
    if len(test_list) == 0:
       return []
    elif isinstance(test_list,list) and type(test_list[0]) in [int,str]:
        return [test_list[0]] + flatten(test_list[1:])
    elif isinstance(test_list,list) and isinstance(test_list[0],list):
        return test_list[0] + flatten(test_list[1:])
    else:
        return flatten(test_list[1:])

我希望能得到一些建议。

最佳答案

这两种情况都可以处理,我认为可以解决一般情况,而不需要任何for循环:

def flatten(S):
    if S == []:
        return S
    if isinstance(S[0], list):
        return flatten(S[0]) + flatten(S[1:])
    return S[:1] + flatten(S[1:])

关于python - 递归展平列表,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12472338/

10-12 16:48