我有以下一段代碼。如何從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或其他東西的扁平列表!
你的問題是無關的'multiprocessing'模塊;你已經得到了你的列表,你只需要將它弄平,如[在這個問題]中的示例所示(https://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of - 列出合蟒)。 – alexis
@alexis我可以直接從pool1.map中的調用中獲取扁平列表嗎? –
爲什麼不呢?它返回一個迭代器,所以你應該能夠直接解壓縮結果:'another_shared_list.extend(e for lst in pool1.map(worker2,numbers)for e in lst)''。 – alexis