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

时间:2017-06-06 10:41:21

标签: 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

打印

[[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]

我应该如何处理它?<​​/ p>

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

1 个答案:

答案 0 :(得分:3)

使用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