【发布时间】: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