Ish*_*att 2 python multiprocessing
我有以下一段代码。
我的工作人员返回一个列表,我想要一个主列表,它是所有列表的并集。
from multiprocessing import Pool, Manager
manager = Manager()
another_shared_list = manager.list()
def worker2(number):
return [x for x in xrange(number)]
numbers = [5,7,2,4]
pool1 = Pool(4)
another_shared_list.extend(pool1.map(worker2, numbers))
print another_shared_list
Run Code Online (Sandbox Code Playgroud)
它打印
[[0, 1, 2, 3, 4], [0, 1, 2, 3, 4, 5, 6], [0, 1], [0, 1, 2, 3]]
Run Code Online (Sandbox Code Playgroud)
正如您可能已经猜到的那样,我希望 another_shared_list 成为
[0,1,2,3,4,0,1,2,3,4,5,6,0,1,0,1,2,3]
Run Code Online (Sandbox Code Playgroud)
我应该如何处理它?
编辑:我知道这似乎是一个扁平化列表问题,不适用于多重处理。但我的偏好是避免使用 itertools。我想要的东西是 another_shared_list 直接从调用 pool1.map 或其他东西中获取扁平列表!
使用itertools.chain:
itertools.chain(*another_shared_list)
Run Code Online (Sandbox Code Playgroud)
工作示例:
another_shared_list = [[0, 1, 2, 3, 4], [0, 1, 2, 3, 4, 5, 6], [0, 1], [0, 1, 2, 3]]
import itertools
list(itertools.chain(*another_shared_list))
[0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 5, 6, 0, 1, 0, 1, 2, 3]
Run Code Online (Sandbox Code Playgroud)
请注意,它chain返回一个迭代器,如果需要,您必须将其消耗到列表中。
或者如下评论:
itertools.chain.from_iterable(another_shared_list) #to avoid unpacking
Run Code Online (Sandbox Code Playgroud)