我试图让这个语句并行运行(在4个线程上)。
[x for x in obj_list if x.attribute == given_attribute]
任何帮助都将不胜感激。
我发现this问题对其他类型的理解很有用,但不适用于像这种情况那样的过滤。
答案 0 :(得分: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