为标题含糊不清表示歉意,我不确定如何简明地描述我的问题。
为简单起见,我编写了一个非常简短的测试代码,该代码演示了我遇到的问题。我正在尝试使用多重处理来创建一个大数据集,以与plt.imshow一起使用来制作热图。
测试代码如下(忽略我仅使用1的事实,因为我说这只是出于演示目的):
import numpy as np
import multiprocessing
G_list = [1,2,3]
r = 6
def test(G):
D = np.cos(G)
E = r*2
return G, D, E
pool = multiprocessing.Pool(1)
r_list = []
for i in range(5):
r += 1
r_list.append(r)
print r_list
for i in range(len(r_list)):
r = r_list[i]
output = pool.map(test,G_list)
print output
此代码的目的是为G_list中G的三个值计算D和E的值,除了我希望它为r的值范围执行此操作。由于pool.map()不接受具有多个输入的函数,因此,我尝试将pool.map()命令简单地放入变化r的for循环中。 结果是:
[7, 8, 9, 10, 11]
[(1, 0.54030230586813977, 6), (2, -0.41614683654714241, 6), (3, -0.98999249660044542, 6)]
[(1, 0.54030230586813977, 6), (2, -0.41614683654714241, 6), (3, -0.98999249660044542, 6)]
[(1, 0.54030230586813977, 6), (2, -0.41614683654714241, 6), (3, -0.98999249660044542, 6)]
[(1, 0.54030230586813977, 6), (2, -0.41614683654714241, 6), (3, -0.98999249660044542, 6)]
[(1, 0.54030230586813977, 6), (2, -0.41614683654714241, 6), (3, -0.98999249660044542, 6)]
您可以看到,pool.map()会按预期方式改变G,但是每个循环的r值都是相同的,尽管事实上在调用pool.map()之前每个循环都对其进行了更改。我的问题是,如何防止使用顶部全局定义的r的值来防止pool.map(),并使其使用我将其更改为每个循环的值?
Python 2.7,非常感谢!
答案 0 :(得分:0)
由于test
仅接受一个输入,因此将输入设为元组。
然后在test
内部,将元组解压缩为单独的变量:
def test(task):
G, r = task
现在,在调用pool.map
时,将元组列表作为第二个参数传递:
tasks = [(G, r) for r in r_list for G in G_list]
output = pool.map(test, tasks)
import numpy as np
import multiprocessing
def test(task):
G, r = task
D = np.cos(G)
E = r*2
return G, D, E
if __name__ == '__main__':
pool = multiprocessing.Pool(1)
G_list = [1,2,3]
r = 6
r_list = [r+i for i in range(1, 6)]
tasks = [(G, r) for r in r_list for G in G_list]
output = pool.map(test, tasks)
print(output)
list comprehension r_list = [r+i for i in range(1, 6)]
等同于
r_list = []
for i in range(1, 6):
r_list.append(r+i)
类似地,列表理解tasks = [(G, r) for r in r_list for G in G_list]
是等效的
tasks = []
for r in r_list:
for G in G_list:
tasks.append((G, r))