[英]How to parallelize a for loop in Python?
一些關於在 Python 中並行化 for 循環的文章已經存在,例如這篇文章,但我不能用它們來處理我的問題。 讓我們舉一個簡單的例子。 我有三個列表:
L1 = [1,2,3]
L2 = [3,4,5]
L3 = [5,6,7]
我想將列表中的每個元素加倍。 我可以這樣做:
for l in [L1,L2,L3] :
for i in range(len(l)) :
l[i] = l[i]*2
請問如何並行化此代碼以並行轉換 L1、L2 和 L3?
請注意,這個例子只是為了有一個清晰易懂的例子,我知道在現實中並行化這樣的快速代碼並不是一個好主意
import asyncio
import time
def background(f):
def wrapped(*args, **kwargs):
return asyncio.get_event_loop().run_in_executor(None, f, *args, **kwargs)
return wrapped
@background
def your_function(argument):
time.sleep(2)
print('function finished for '+str(argument))
for i in range(10):
your_function(i)
print('loop finished')
from multiprocessing import Pool
L1 = [1,2,3]
L2 = [3,4,5]
L3 = [5,6,7]
def f(li):
return [x * 2 for x in li]
if __name__ == '__main__':
with Pool(4) as pool:
print(pool.map(f, [L1, L2, L3]))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.