![](/img/trans.png)
[英]Python/Pandas: Using built-in functions as arguments in user-defined function
[英]Python: Passing functions with arguments to a built-in function?
像這個問題,我想傳遞一個帶有參數的函數。 但我想將其傳遞給內置函數。
例:
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'))
這是做同樣事情的列表理解
import os
[f for f in files if os.path.splitext(f)[1]=="."+ex]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.