Skip to main content
 首页 » 编程设计

Python:将带有参数的函数传递给内置函数

2025年05月04日10dflying

像这样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 的函数只接受一个参数,即序列中的项目。

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

请您参考如下方法:

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'))