【问题标题】:Python: Passing functions with arguments to a built-in function?Python:将带参数的函数传递给内置函数?
【发布时间】:2011-03-11 13:01:58
【问题描述】:

像这样question 我想传递一个带参数的函数。但我想将它传递给内置函数。

例子:

files = [ 'hey.txt', 'hello.txt', 'goodbye.jpg', 'howdy.gif' ]

def filterex(path, ex):
  pat = r'.+\.(' + ex + ')$'
  match = re.search(pat, path)         
  return match and match.group(1) == ex) 

我可以将该代码与 for 循环和 if 语句一起使用,但使用 filter(func, seq) 会更短且可读性更强。但是,如果我理解正确的话,您使用 filter 的函数只需要一个参数,即序列中的项目。

所以我想知道是否可以传递更多参数?

【问题讨论】:

  • 使用列表理解。它会比过滤器更快,更容易阅读
  • 你有几个错别字。它应该是 match = return True(或者你可以只是 return match and match.group(1) == ex
  • 感谢 Matthew 我调整了它。

标签: python refactoring


【解决方案1】:

这是一个做同样事情的列表推导

import os
[f for f in files if os.path.splitext(f)[1]=="."+ex]

【讨论】:

  • 非常感谢您。我在代码的其他部分有列表理解,但似乎我没有连接到我的过滤器函数。我会用“我是新借口”。
【解决方案2】:
def make_filter(ex):
    def do_filter(path):
        pat = r'.+\.(' + ex + ')$'
        match = re.search(pat, path)
        return match and match.group(1) == ex
    return do_filter

filter(make_filter('txt'), files)

或者如果您不想修改 filterex:

filter(lambda path: filterex(path, 'txt'), files)

您可以按照 gnibbler 的建议使用列表推导:

[path for path in files if filterex(path, 'txt')]

您还可以使用生成器推导式,如果您的列表很大,这可能特别有用:

(path for path in files if filterex(path, 'txt'))

【讨论】:

  • 感谢您的回答 Matthew Flaschen 我很感激。
猜你喜欢
  • 2016-06-29
  • 2012-06-19
  • 2015-01-23
  • 1970-01-01
  • 1970-01-01
  • 2014-11-27
  • 2019-03-29
  • 2010-10-22
相关资源
最近更新 更多