python - 带有条件的 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()
由于我不再有权访问枚举器,如何将其添加到我调用的函数中?
很感谢任何形式的帮助!
一切顺利,雪
解决方案
您可以对 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)
推荐阅读
- vb.net - 我正在尝试使用多线程读取所有带有 2 个线程的行以获取不同的文本而不是相同的文本?
- python - 从我的驱动器中选择的文件夹列表创建子文件夹
- ios - 无法从 AppDelegate 导航到 UIViewController
- scala - Spark:从窗口获取行值
- d3.js - 如何在 D3/dagre-D3/javascript 中创建决策树/流程图?
- python - 使用 Cython 向 Python 公开具有继承的 C++ 类时如何避免基类重新定义
- angular - 是否可以使用高图从左到右创建网络图作为树图?
- python - 在 NumPy 中创建随机 float 和 float64 数组
- azure-devops - 在 Azure Devops 托管代理上安装或使用软件
- html - 如何在悬停时更改无序列表中列表项的 z-index?