首页 > 解决方案 > 带有条件的 Python ProcessPoolExecutor

问题描述

我必须处理大量的图像数据,并想使用包中的.map()函数concurrent.futures来加速它。目标是遍历目录中的所有图像,处理它们,然后将它们保存在另一个目录中。这本身不是问题,但我想将 90% 的已处理图像保存在一个目录中,其余 10% 保存在另一个目录中。我怎样才能做到这一点.map()

没有.map()我列举图像然后说:

if enumerator < (len(directory) * 0.9):
     save image in one directory
else:
     save image in another directory

.map()由于我不再有权访问枚举器,如何将其添加到我调用的函数中?

很感谢任何形式的帮助!

一切顺利,雪

标签: pythonmultiprocessingconditional-statementsenumerateconcurrent.futures

解决方案


您可以对 map 函数使用其他参数,这些参数应该是迭代器,每个迭代器的 1 个元素将传递给您的作业池所经历的每次迭代:

def my_function(file, sorting_bool):
  if sorting_bool:
    # do this with `file`
  else:
    # do that with `file`

total = len(directory)
sorter = lambda x: x < 0.9 * total
dir_sorted = map(sorter, range(total))
pool.map(my_function, directory, dir_sorted)

一般来说,对于其他任务,您可以向您的工作发送工作 ID 和总 ID:

def my_function(file, job_id, total_jobs):
  if job_id < total_jobs * 0.9:
    # Do this
  else:
    # Do that

total = len(directory)
pool.map(my_function, directory, range(total), lambda: total)

然后在你的内部使用你想要的那些数字my_function

如果您的作业总数未知,您仍然可以创建一个生成器来创建一个计数器:

def counter():
  i = 0
  while True:
    yield i
    i += 1

pool.map(my_function, counter(), other, args)

推荐阅读