Pic*_*els 1 python refactoring
像这个问题我想传递一个带参数的函数.但我想将它传递给内置函数.
例:
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)
Run Code Online (Sandbox Code Playgroud)
我可以使用带有for循环和if语句的代码,但它更短,使用filter(func,seq)可能更具可读性.但是,如果我理解正确,您使用过滤器的函数只接受一个参数,该参数是序列中的项目.
所以我想知道是否可以传递更多的论据?
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)
Run Code Online (Sandbox Code Playgroud)
或者,如果您不想修改filterex:
filter(lambda path: filterex(path, 'txt'), files)
Run Code Online (Sandbox Code Playgroud)
您可以使用列表推导,如gnibbler所建议的:
[path for path in files if filterex(path, 'txt')]
Run Code Online (Sandbox Code Playgroud)
您还可以使用生成器理解,如果您有一个大型列表,这可能会特别有用:
(path for path in files if filterex(path, 'txt'))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
322 次 |
| 最近记录: |