首页 > 解决方案 > imap 无序值访问

问题描述

我有以下情况,说明了一个更复杂的情况。

依赖项:

#formula
def cube_rand(x):

  c = x**3
  time.sleep(random.random())

  return (x,c)

#dataframe to be used
dict_input = {
              'col1': ['a','b','c'],
              'col2': [1,2,3]
             }

df_test = pd.DataFrame(dict_input)

imap 实例:

from multiprocessing import Pool

start = time.time()

p=Pool(8)

results = p.imap_unordered(cube_rand, (index for index,row in df_test.iterrows()))

print(results)

done = time.time()

print("processing time: ", done-start)

我想为定义的数据框中的每一行打印无序的对 ("index","index^3")。但是,我收到以下输出:

<multiprocessing.pool.IMapUnorderedIterator object at 0x7fb5af0cbd50>
processing time:  0.15177679061889648

关于如何解决这个问题的任何猜测?

谢谢

标签: pythonmultiprocessing

解决方案


您需要迭代imap_unordered调用的结果:

for x in p.imap_unordered(cube_rand, (index for index,row in df_test.iterrows())):
    print(x)

输出:

(0, 0)
(2, 8)
(1, 1)
processing time:  1.1946678161621094

推荐阅读