首页 > 解决方案 > 如何用 concurrent.futures 替换嵌套循环?

问题描述

说,我有以下循环:

for i in range(50):
   for j in range(50):
      for k in range(50):
         for l in range(50):
             some_function(i,j,k,l)

some_function恰好是很多小文件的网络爬虫,所以并行化它是有意义的。

但据我所知,concurrent.futures 只接受一个迭代器,所以我不确定如何处理这个问题。我能做的就是将它们(其中两个)表示为单个迭代器,例如:

def in_between_function(a):
    x = math.floor(a/5)
    y = a % y
    some_function(x,y)

with concurrent.futures.ThreadPoolExecutor(max_workers=100) as executor:
   future = executor.map(in_between_function, range(50*50))

看起来还不错,但我想正确地做到这一点;如果我将其扩展到更多迭代器、负数或迭代器不是线性的,那么这将是一场噩梦。

标签: pythonconcurrent.futures

解决方案


推荐阅读