【问题标题】:Python: apply list of functions to each element in listPython:将函数列表应用于列表中的每个元素
【发布时间】:2015-05-12 14:14:42
【问题描述】:

假设我有元素列表 content = ['121\n', '12\n', '2\n', '322\n'] 和函数列表 fnl = [str.strip, int]

所以我需要将fnl 中的每个函数依次应用于content 中的每个元素。 我可以通过几个电话map 来做到这一点。

另一种方式:

xl = lambda func, content: map(func, content)
for func in fnl:
    content = xl(func, content) 

我只是想知道是否有更 Pythonic 的方式来做到这一点。

没有单独的功能?通过单个表达式?

【问题讨论】:

    标签: python python-2.7 lambda


    【解决方案1】:

    您可以在此处的列表理解中使用reduce() function

    [reduce(lambda v, f: f(v), fnl, element) for element in content]
    

    演示:

    >>> content = ['121\n', '12\n', '2\n', '322\n']
    >>> fnl = [str.strip, int]
    >>> [reduce(lambda v, f: f(v), fnl, element) for element in content]
    [121, 12, 2, 322]
    

    这会将每个函数依次应用于每个元素,就像嵌套调用一样;对于 fnl = [str.strip, int] 转换为 int(str.strip(element))

    在 Python 3 中,reduce() 被移动到了functools module;为了向前兼容,您可以从 Python 2.6 以后的模块中导入它:

    from functools import reduce
    
    results = [reduce(lambda v, f: f(v), fnl, element) for element in content]
    

    请注意,对于int() 函数,数字周围是否有多余的空格无关紧要; int('121\n') 无需删除换行符即可工作。

    【讨论】:

      【解决方案2】:

      您正在描述列表推导的基本用法:

      >>> content = ['121\n', '12\n', '2\n', '322\n']
      >>> [int(n) for n in content]
      [121, 12, 2, 322]
      

      请注意,您不需要调用 strip 来转换为整数,一些空格可以很好地处理。

      如果您的实际用例更复杂,并且您希望在推导中任意组合多个函数,但是,我从here 中找到了相当pythonic 的想法:

      def compose(f1, f2):
          def composition(*args, **kwargs):
              return f1(f2(*args, **kwargs))
          return composition
      
      def compose_many(*funcs):
          return reduce(compose, funcs)
      

      【讨论】:

        猜你喜欢
        • 2014-09-24
        • 2010-10-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-27
        相关资源
        最近更新 更多