并行处理python中的循环 [英] Parallelize for loops in python

查看:175
本文介绍了并行处理python中的循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能在python中并行化以下代码?我想知道如何使用map和lambda函数转换此代码.

Is there any possibility to parallelize the following code in python? I was wondering how to convert this code with map and lambda functions..

values = (1,2,3,4,5 )

def op(x,y):
    return x+y

[(i, j, op(i, j))
        for i in values
        for j in values
        if i is not j]

推荐答案

您可以将函数op与多处理和映射并行化:

You can parallelize the function op with multiprocessing and map:

from multiprocessing.dummy import Pool as ThreadPool
from itertools import permutations

pool = ThreadPool(4)  # Number of threads

values = (1,2,3,4,5)
aux_val = [(i, j) for i,j in permutations(values,2)]

def op(tupx):
    result = (tupx[0], tupx[1], tupx[0] + tupx[1])
    return result

results = pool.map(op, aux_val)

这篇关于并行处理python中的循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆