【问题标题】:Filtering function for an arbitrary nested list任意嵌套列表的过滤函数
【发布时间】:2017-05-09 21:49:02
【问题描述】:

由于双重条件,我不知道如何将此函数编写为 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 的方式是什么来编写这样一个过滤任意嵌套列表的函数?

【问题讨论】:

  • e 不是liste <= 10 的情况下是否要返回None?此外,比双重条件更严重的是函数的递归性质。当函数没有名称可调用时,您希望如何递归?
  • “写这样一个函数的pythonic方法是什么”——不是作为lambda?
  • @RoryDaulton 不,这就是我必须过滤掉它的原因
  • 那要返回什么?函数总是返回something——如果没有遇到return 语句,则返回None
  • 如果你用文字解释你想让这个函数做什么呢?

标签: python python-2.7 list lambda functional-programming


【解决方案1】:

首先,通过def 将过滤或映射函数定义为常规函数并没有错,如果这有助于提高可读性 - 请记住"Readability counts" and "Sparse is better than dense"。仅仅因为语言中有内联lambda 函数,并不意味着您必须将逻辑压缩到其中。

由于您最终想要为任意列表深度构建通用解决方案,您可以递归地应用过滤函数,通过map() + filter() 删除None 值: p>

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

【讨论】:

    【解决方案2】:

    好吧,这不是最佳实践,但您可以创建一个 lambda 函数:使用括号对条件进行分组:

    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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-10
      • 2019-05-23
      • 2023-02-11
      • 1970-01-01
      相关资源
      最近更新 更多