我想在带有生成器功能的python中使用多重处理
假设我有大量的列表big_list
,我想使用多重处理来计算值。如果我使用返回值的“传统”函数,这很简单:
import concurrent
def compute_function(list_of_lists):
return_values = [] ## empty list
for list in list_of_lists:
new_value = compute_something(list) ## compute something; just an example
return_values.append(new_value) ## append to list
return return_values
with concurrent.futures.ProcessPoolExecutor(max_workers=N) as executor:
new_list = list(executor.map(compute_function, big_list))
但是,以这种方式使用列表会占用大量内存。所以我想改用生成器函数:
import concurrent
def generator_function(list_of_lists):
for list in list_of_lists:
new_value = compute_something(list) ## compute something; just an example
yield new_value
with concurrent.futures.ProcessPoolExecutor(max_workers=N) as executor:
new_list = list(executor.map(generator_function, big_list))
我的问题是,您不能腌制发电机。对于其他数据结构,有一些解决方法可以解决此问题,但对于我认为的生成器而言,没有解决方法。
我该如何完成?
您可以使用big_list
迭代子列表,在itertools.chain.from_iterable
中更深入地进行枚举。
import concurrent
import itertools
def compute_function(item):
return compute_something(item)
with concurrent.futures.ProcessPoolExecutor(max_workers=N) as executor:
for result in executor.map(compute_function,
itertools.chain.from_iterable(big_list)):
print(result)
generator只是一个保留状态的奇特循环,它类似于迭代器逻辑,它为您提供了next
,hasNext
和类似的api,因此您的循环将要求迭代器提供下一项(只要因为有下一项)
发生器的植入完全取决于显影剂,可以通过]实施>
for i in [1,2,3,4]
for line in file
range(100)
中的>]所有人都有一个共同的要求,在这种情况下,生成器需要保持其当前状态,以便它将在下一个状态中知道yield
的内容,因此使其非常多[[stateful,这反过来又使它成为非常糟糕的选择用于多处理...