Python 并行更新阵列?
假设我有一个python列表:Python 并行更新阵列?,python,list,multiprocessing,Python,List,Multiprocessing,假设我有一个python列表: def func(arr, i): arr[i] = arr[i] + ' hello!' xyz = ['a','b','c','d','e'] for i in range(len(xyz)): func(xyz, i) for i in xyz: print i 最后 a hello! b hello! c hello! d hello! e hello! 由于我的列表非常大,如何使用multicore并行更新列表中的元
def func(arr, i):
arr[i] = arr[i] + ' hello!'
xyz = ['a','b','c','d','e']
for i in range(len(xyz)):
func(xyz, i)
for i in xyz:
print i
最后
a hello!
b hello!
c hello!
d hello!
e hello!
由于我的列表非常大,如何使用multicore并行更新列表中的元素
我已经搜索了所有地方,但似乎找不到答案。从问题中发现,您希望用新值替换列表中某项的当前值:
for position, value in enumerate(xyz):
xyz[position] = '%s hello!' % value
给出:['a hello!'、'b hello!'、'c hello!'、'd hello!'、'e hello!']多亏了@roganjosh的建议,我才能够找到答案:
import numpy as np
from multiprocessing import Pool
arr = ['a','b','c','d','e','f','g']
def edit_array(i):
return arr[i] + ' hello!'
if __name__=='__main__':
pool = Pool(processes=4)
list_start_vals = range(len(arr))
array_2D = pool.map(edit_array, list_start_vals)
pool.close()
print array_2D
这里有一个相对简单的方法,可以使用
多处理
模块来实现:
import functools
import multiprocessing
def func(arr, i):
arr[i] = arr[i] + ' hello!'
if __name__ == '__main__':
manager = multiprocessing.Manager() # Create a manager to handle shared object(s).
xyz = manager.list(['a','b','c','d','e']) # Create a proxy for the shared list object.
p = multiprocessing.Pool(processes=4) # Create a pool of worker processes.
# Create a single arg function with the first positional argument (arr) supplied.
# (This is necessary because Pool.map() only works with functions of one argument.)
mono_arg_func = functools.partial(func, xyz)
p.map(mono_arg_func, range(len(xyz))) # Run func in parallel until finished
for i in xyz:
print(i)
输出:
你好!
b你好!
c你好!
d你好!
你好!
请注意,如果列表很大,这将是而不是,因为在不同的任务(在不同的内存空间中运行)之间共享对大型对象的访问需要大量开销
更好的方法是使用
多处理.Queue
,根据文档,“使用管道和一些锁/信号量”实现(与共享列表对象相反,共享列表对象的全部内容必须经过多次pickle和unpickle)。您的预期输出是什么?您的问题不清楚。您好,Haranadh,预期的输出是一个更新的列表:a hello!b你好!c你好!d你好!你好
但我想并行执行,因为列表的大小可能包含数千个元素。您可以使用一个?让python来决定会更好。你好,Martin,谢谢你的回复。但是我如何并行处理呢?使用多线程或多处理来分发工作,正如罗甘霍什在上面的评论中所建议的那样