python多进程与两个列表比较
问题描述:
我有问题multiprocess
在python3.5
。python多进程与两个列表比较
如果我有两个列表,如:
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
...
与代码。
有什么方法可以达到目标(必须使用多进程)吗?
答
我想你想尝试一个简单的例子,然后在一个非常大的数字集合上使用它,并使用更复杂的函数。
这是一个打印你想要的东西,使用多处理程序,并应扩展更大的列表和更复杂的功能的程序。
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
你是什么意思? –
@MadPhysicist我想处理大数据,所以我必须使用多进程来处理计算。但我不知道如何使用多处理来处理两个列表 – chilun
我的意思是“我无法得到我想要的结果”。是一个SO问题中的红旗。这太含糊 –