本文介紹了如何讓 Pool.map 采用 lambda 函數的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
限時送ChatGPT賬號..
我有以下功能:
def copy_file(source_file, target_dir):
pass
現在我想使用 multiprocessing
來一次執行這個函數:
Now I would like to use multiprocessing
to execute this function at once:
p = Pool(12)
p.map(lambda x: copy_file(x,target_dir), file_list)
問題是,lambda 不能被腌制,所以這失敗了.解決此問題的最簡潔(pythonic)方法是什么?
The problem is, lambda's can't be pickled, so this fails. What is the most neat (pythonic) way to fix this?
推薦答案
使用函數對象:
class Copier(object):
def __init__(self, tgtdir):
self.target_dir = tgtdir
def __call__(self, src):
copy_file(src, self.target_dir)
運行你的 Pool.map
:
p.map(Copier(target_dir), file_list)
這篇關于如何讓 Pool.map 采用 lambda 函數的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!