由于双重条件,我不知道如何将此函数编写为 lambda:
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]]
另外,pythonic 的方式是什么来编写这样一个过滤任意嵌套列表的函数?
最佳答案
首先,通过 def
将过滤或映射函数定义为常规函数并没有错,如果这对可读性有好处的话 - 记住 "Readability counts" and "Sparse is better than dense" .仅仅因为语言中有内联 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))
请注意,Python 3.x 需要 list()
,因为 filter()
does not return a list .
演示:
>>> 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]]
关于python - 任意嵌套列表的过滤函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41314144/