Can I flatten a list using recursive function and

2019-04-17 16:01发布

问题:

This is only for self learning of the concept and might not have practical use

My question is

  1. can I use only recursive function and list comprehension to flatten a unknown level of nested list?

  2. If 1 is possible, can I only use list comprehension + lambda function to get the same purpose?

So far this all I can get but it seems not working.

l=[1,[2,3],[4,5,[6,7,8,9]]] # assuming unknown level of nesting

def fun_d(x):
    return [fun_d(e) if isinstance(e,list) else e for e in x]

fun_d(l)

Out[25]: [1, [2, 3], [4, 5, [6, 7, 8, 9]]]

回答1:

You can though it is a little strange:

def fun_d(x):
    return [i for e in x for i in (fun_d(e) if isinstance(e,list) else [e])]

In[] :
l=[1,[2,3],[4,5,[6,7,8,9]]]
fun_d(l)

Out[]:
[1, 2, 3, 4, 5, 6, 7, 8, 9]

You may want to use Sequence rather than list so other types of sequences would also be flattened.

from typing import Sequence

def fun_d(x):
    return [i for e in x for i in (fun_d(e) if isinstance(e, Sequence) and not isinstance(e, str) else [e])]

A named lambda is trivial, for a truly anonymous lambda you can use a y-combinator

And just to show how ridiculous this is, an anonymous recursive lambda:

In []:
lis = [1,[2,3],[4,5,[6,[7,8],9]]]
(lambda f: f(f))(lambda f: (lambda fun_d: lambda x: [i for e in x for i in (fun_d(e) if isinstance(e, list) else [e])])(lambda x: f(f)(x)))(lis)

Out[]:
[1, 2, 3, 4, 5, 6, 7, 8, 9]