Flattening a list recursively [duplicate]

2019-01-13 23:14发布

Possible Duplicate:
Flatten (an irregular) list of lists in Python

I am having trouble using python to recursively flatten a list. I have seen a number of methods that require list comprehension and various methods requiring imports however I am looking for a very basic method to recursively flatten a list of varying depth that does not use any for loops either. I had a series of test however there are two I cannot pass

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

My code

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

I would appreciate some advice.

4条回答
虎瘦雄心在
2楼-- · 2019-01-13 23:35
li=[[1,[[2]],[[[3]]]],[['4'],{5:5}]]
flatten=lambda l: sum(map(flatten,l),[]) if isinstance(l,list) else [l]
print flatten(li)
查看更多
女痞
3楼-- · 2019-01-13 23:42

Here's a possible solution without any loops or list comprehensions, just using recursion:

def flatten(test_list):
    if isinstance(test_list, list):
        if len(test_list) == 0:
            return []
        first, rest = test_list[0], test_list[1:]
        return flatten(first) + flatten(rest)
    else:
        return [test_list]
查看更多
爱情/是我丢掉的垃圾
4楼-- · 2019-01-13 23:45

Well, if you want it a lisp way, let's have it.

atom = lambda x: not isinstance(x, list)
nil  = lambda x: not x
car  = lambda x: x[0]
cdr  = lambda x: x[1:]
cons = lambda x, y: x + y

flatten = lambda x: [x] if atom(x) else x if nil(x) else cons(*map(flatten, [car(x), cdr(x)]))
查看更多
神经病院院长
5楼-- · 2019-01-13 23:49

This handles both of your cases, and I think will solve the general case, without any for loops:

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:])
查看更多
登录 后发表回答