I can't find out how to write this function as a lambda because of the double conditional:
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 such a function that filters arbitrarily nested lists?
First of all, there is nothing wrong with defining a filtering or mapping function as a regular function via def
if it would be a benefit to readability - remember "Readability counts" and "Sparse is better than dense". Just because there are inline lambda
function in the language, does not mean you have to squeeze your logic into it.
Since you eventually want to build a generic solution for an arbitrary list depth, you can recursively apply the filtering function via map()
+ filter()
to remove the None
values:
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))
Note that list()
would be needed on Python 3.x, since filter()
does not return a list.
Demo:
>>> 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]]
Well, this is not a best practice, but you can create a lambda function: use parenthesis to group conditions:
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]]
For python 3 users:
f = lambda e: list(filter(None, [f(y) for y in e])) if isinstance(e, list) else (e if e > 10 else None)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With