2015-08-17 15 views
1

我试图让这个语句并行运行(4线程)。在Python中并行化这个列表理解

[x for x in obj_list if x.attribute == given_attribute] 

任何帮助,将不胜感激。

我发现this问题对其他类型的理解有用,但不适用于像这种情况下的过滤。

+2

请参阅该文档[这里](https://docs.python.org/3/library/concurrent.futures.html#processpoolexecutor-例如),你可以用'ThreadPoolExecutor'替换'ProcessPoolExecutor'。 – Horba

回答

1

您可以使用您提供的示例中所述的Pool。这种类型的作品,但你必须在事后删除None结果:

import multiprocessing as mp 

class Thing: 
    def __init__(self, y): 
     self.attribute = y 

def square(thing, given_attribute): 
    if thing.attribute == given_attribute: 
     return thing 

given_attribute = 4 
x = [Thing(i) for i in range(10)] # List of objects to process 

if __name__ == '__main__': 
    pool = mp.Pool(processes=4) 
    results = [pool.apply(square, args=(x[i], given_attribute,)) for i in range(10)] 
    r = [i for i in results if i is not None] # Remove the None results 
    print r