Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/304.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用多处理在powerset上迭代_Python_Python 3.x_Multiprocessing - Fatal编程技术网

Python 使用多处理在powerset上迭代

Python 使用多处理在powerset上迭代,python,python-3.x,multiprocessing,Python,Python 3.x,Multiprocessing,我有一个python列表的powerset生成器,我想使用多处理模块对这些集合的元素进行一些计算。我的代码如下所示: def powerset(seq): '''Returns all the subsets of the list. This is a generator.''' if len(seq) == 0: yield seq if len(seq) == 1: yield seq yield [] elif len(seq) > 1:

我有一个python列表的powerset生成器,我想使用多处理模块对这些集合的元素进行一些计算。我的代码如下所示:

def powerset(seq): 
  '''Returns all the subsets of the list. This is a generator.'''
  if len(seq) == 0:
    yield seq
  if len(seq) == 1:
    yield seq 
    yield []
  elif len(seq) > 1: 
    for item in powerset(seq[1:]):
      yield [seq[0]]+item
      yield item

def job(l):
  # do some calculation with the list l
  return do_some_hard_work(l)

def calculate():
  pool_size = multiprocessing.cpu_count() * 2
  pool = multiprocessing.Pool(processes=pool_size, maxtasksperchild=2)
  pool_outputs = pool.map(job, powerset(list(range(1,10)))
  pool.close()
  pool.join()

  return sum(pool_outputs)

问题在于动力集功能是发电机,无法工作。但是我不能更换发电机,因为在计算之前生成孔动力集需要很多时间和内存。有人知道我如何解决这个问题吗?

如果问题是你不想把整个powerset放在一个列表中,你可以使用,它会一次消耗你的迭代器
chunksize
元素,并将它们发送给工作进程,而不是将整个事情转换成一个列表并将其分块

pool_size = multiprocessing.cpu_count() * 2
pool = multiprocessing.Pool(processes=pool_size, maxtasksperchild=2)
pool_outputs = pool.imap(job, powerset(list(range(1,10))), chunksize=<some chunksize>)
pool.close()
pool.join()

“一个发电机,它将不工作”从我在一个小列表上看到的,它提供了所需的答案。什么是“不工作”?您可以将生成器传递到
池.map
,只需知道它将在任何项目发送到工作进程之前转换为列表。谢谢!这正是我要找的!
chunksize, extra = divmod(len(iterable), len(pool_size) * 4)
if extra:
    chunksize += 1