2017-08-29 74 views
1

我有問題multiprocesspython3.5python多進程與兩個列表比較

如果我有兩個列表,如:

xlist = [1,2,3] 
ylist = [4,5,6] 

,我想做的事:

for i in xlist: 
    for j in ylist: 
     print (i*j) 

輸出

4 
5 
6 
8 
10 
12 
12 
15 
18 

我嘗試這樣做,像這樣用多進程:

import multiprocessing 

global xlist 
xlist = [1,2,3] 
ylist = [4,5,6] 

def product(ylist): 
    for x in xlist: 
     for y in ylist: 
      print (x,y) 
    return 'OK' 

if __name__ == "__main__": 
    pool = multiprocessing.Pool() 
    results = [] 
    for i in range(0, len(ylist)): 
     result = pool.apply_async(job, args=(ylist,)) 
     results.append(result) 
     # print (result.get()) 
    pool.close() 
    pool.join() 

for result in results: 
    print(result.get()) 

但我無法得到上面的輸出顯示。我的輸出將是

1 4 
1 5 
1 6 
2 4 
2 5 
2 6 
3 4 
3 5 
3 6 
1 4 
1 5 
1 6 
2 4 
2 5 
2 6 
3 4 
3 5 
3 6 
1 4 
1 5 
... 

與代碼。

有什麼方法可以達到目標(必須使用多進程)嗎?

+0

你是什麼意思? –

+0

@MadPhysicist我想處理大數據,所以我必須使用多進程來處理計算。但我不知道如何使用多處理來處理兩個列表 – chilun

+2

我的意思是「我無法得到我想要的結果」。是一個SO問題中的紅旗。這太含糊 –

回答

1

我想你想嘗試一個簡單的例子,然後在一個非常大的數字集合上使用它,並使用更復雜的函數。

這是一個打印你想要的東西,使用多處理程序,並應擴展更大的列表和更復雜的功能的程序。

import multiprocessing 

xlist=[1,2,3] 
ylist=[4,5,6] 

def enum_tasks(): 
    for x in xlist: 
    for y in ylist: 
     yield (x,y) 

def product(xy): 
    x,y = xy 
    return x * y 

if __name__ == '__main__': 
    CHUNK_SIZE = multiprocessing.cpu_count() 
    pool = multiprocessing.Pool() 
    for result in pool.imap(product, enum_tasks(), CHUNK_SIZE): 
    print result 
+0

感謝您的幫助!那是我需要的。 – chilun