[英]Python: Passing functions with arguments to a built-in function?
like this question I want to pass a function with arguments. 像这个问题,我想传递一个带有参数的函数。 But I want to pass it to built-in functions.
但我想将其传递给内置函数。
Example: 例:
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)
I could use that code with a for loop and an if statement but it's shorter and maybe more readable to use filter(func, seq). 我可以将该代码与for循环和if语句一起使用,但是使用filter(func,seq)的过程更短,可读性更好。 But if I understand correctly the function you use with filter only takes one argument which is the item from the sequence.
但是,如果我正确理解了与filter一起使用的函数,则仅采用一个参数,该参数是序列中的项。
So I was wondering if it's possible to pass more arguments? 所以我想知道是否可以传递更多参数?
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)
Or if you don't want to modify filterex: 或者,如果您不想修改filterex:
filter(lambda path: filterex(path, 'txt'), files)
You could use a list comprehension, as suggested by gnibbler: 您可以使用列表理解,如gnibbler所建议:
[path for path in files if filterex(path, 'txt')]
You could also use a generator comprehension, which might be particularly useful if you had a large list: 您还可以使用生成器理解,如果列表很大,这可能特别有用:
(path for path in files if filterex(path, 'txt'))
Here is a list comprehension that does the same thing 这是做同样事情的列表理解
import os
[f for f in files if os.path.splitext(f)[1]=="."+ex]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.