Filter function for an arbitrary nested list

I can't find out how to write this function as a lambda due to a double conditional expression:

def f(e):
    if not isinstance(e,list):
        if e >10:
            return e
    else:
        return filter(None,[f(y) for y in e])
my_list=[[1], [2,[3,12, [4,11,12]]], [5,6,13,14],[15]]

>>> f(my_list)
[[[12, [11, 12]]], [13, 14], [15]]

Also, what would be the pythonic way to write a function that filters out arbitrary nested lists?

+4
source share
2 answers

, def, - " " " " . , lambda, , .

, map() + filter(), None:

def filter_function(e):
    if isinstance(e, list):
        return filter(None, map(filter_function, e))
    elif e > 10:
        return e

my_list = list(filter_function(my_list))  

, list() Python 3.x, filter() .


:

>>> my_list = [[1], [2, [3, 12, [4, 11, 12]]], [5, 6, 13, 14], [15]]
>>> 
>>> def filter_function(e):
...     if isinstance(e, list):
...         return filter(None, map(filter_function, e))
...     elif e > 10:
...         return e
... 
>>> 
>>> print(list(filter_function(my_list)))
[[[12, [11, 12]]], [13, 14], [15]]
+5

, , -: :

f = lambda e: filter(None, [f(y) for y in e]) if isinstance(e, list) else (e if e > 10 else None)

my_list = [[1], [2, [3, 12, [4, 11, 12]]], [5, 6, 13, 14], [15]]

>>> f(my_list)
[[[12, [11, 12]]], [13, 14], [15]]

python 3:

f = lambda e: list(filter(None, [f(y) for y in e])) if isinstance(e, list) else (e if e > 10 else None)
+2

Source: https://habr.com/ru/post/1664777/


All Articles