所以我有下面的代码可以正常工作:
from concurrent.futures import ProcessPoolExecutor
import itertools
def grid_search_helper(vec_input):
v1 = vec_input[0]
v2 = vec_input[1]
v3 = vec_input[2]
d = {'v1' : v1, 'v2' : v2, 'v3' : v3}
return(d)
idx = range(0,10)
cutoff = np.ndarray.tolist(np.arange(0.6,0.95,0.05))
opt = [2]
iters = itertools.product(idx, cutoff, opt)
with ProcessPoolExecutor(max_workers = 11) as executor:
for res in executor.map(grid_search_helper,iters):
print(res)
然后我尝试使用zip()打印出ProcessPoolExecuter正在处理的可迭代项,但是当我运行以下代码时,什么都没打印出来:
from concurrent.futures import ProcessPoolExecutor
import itertools
def grid_search_helper(vec_input):
v1 = vec_input[0]
v2 = vec_input[1]
v3 = vec_input[2]
d = {'v1' : v1, 'v2' : v2, 'v3' : v3}
return(d)
idx = range(0,10)
cutoff = np.ndarray.tolist(np.arange(0.6,0.95,0.05))
opt = [2]
iters = itertools.product(idx, cutoff, opt)
with ProcessPoolExecutor(max_workers = 11) as executor:
for res, itr in zip(executor.map(grid_search_helper,iters), iters):
print(res, itr)
我不知道为什么。有人可以帮忙吗?
答案 0 :(得分:2)
与压缩函数和迭代器无关。
问题是您使用相同的迭代器两次:
# v v
for res, itr in zip(executor.map(grid_search_helper, iters), iters):
...
它第一次传递给map
时被消耗。到再次传递给zip
时,它已经是空的了,因此zip
返回了一个空的生成器,没有任何要迭代的内容。
使用itertools.tee
创建同一迭代器的两个副本。
it1, it2 = itertools.tee(itertools.product(idx, cutoff, opt))
with ProcessPoolExecutor(max_workers = 11) as executor:
for res, itr in zip(executor.map(grid_search_helper,it1), it2):
print(res, itr)
答案 1 :(得分:1)
当它尝试执行zip(..., iters)
时,先前填充的iters
已经为空,因为executor.map(grid_search_helper, iters)
已经消耗了所有项目。
因此,您实际上是将一个空的迭代器传递给zip()
。