如何从Python中的多处理返回平展列表?

问题描述:

我有以下一段代码。如何从Python中的多处理返回平展列表?

我的工作人员返回一个列表,我想要一个主列表,它是所有列表的联合。

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 

它打印

[[0, 1, 2, 3, 4], [0, 1, 2, 3, 4, 5, 6], [0, 1], [0, 1, 2, 3]] 

正如你可能已经猜到我想another_shared_list是

[0,1,2,3,4,0,1,2,3,4,5,6,0,1,0,1,2,3] 

我应该如何处理它?

编辑: 我知道这似乎是一个扁平的列表问题,而不是多处理。但我的偏好是避免itertools。我想要的东西,这样another_shared_list直接从调用pool1.map或其他东西的扁平列表!

+0

你的问题是无关的'multiprocessing'模块;你已经得到了你的列表,你只需要将它弄平,如[在这个问题]中的示例所示(https://*.com/questions/952914/making-a-flat-list-out-of-list-of - 列出合蟒)。 – alexis

+0

@alexis我可以直接从pool1.map中的调用中获取扁平列表吗? –

+0

为什么不呢?它返回一个迭代器,所以你应该能够直接解压缩结果:'another_shared_list.extend(e for lst in pool1.map(worker2,numbers)for e in lst)''。 – alexis

使用itertools.chain

itertools.chain(*another_shared_list) 

工作例如:

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] 

注意chain返回一个迭代器,你有,如果你需要它它消耗到列表中。

或者像下面评论说:

itertools.chain.from_iterable(another_shared_list) #to avoid unpacking 
+0

而'chain.from_iterable()'可以避免解包。 –

+0

@ @IljaEverilä的工作示例 –