【问题标题】:Iterating dict.items() when passed to Pool map function gives weird results传递给 Pool map 函数时迭代 dict.items() 会产生奇怪的结果
【发布时间】:2015-07-13 23:41:32
【问题描述】:

我正在尝试在 Python 3 中进行一些多处理。尝试迭代从多处理模块通过 Pool.map() 方法传递的 dict 项时,我发现了一些奇怪的东西。

from multiprocessing.pool import Pool

def reduce(lines):
    print(lines[0])

pool = Pool(processes=8)
dataset = [(1, {"foo": "bar"}), (2, {"foo": "bar"})]
print(dataset[0])
a = pool.map(reduce, dataset)

正如您在此处看到的,print(dataset[0]) 将打印:

(1, {'foo': 'bar'})

而 print(lines[0]) 将打印:

1
2

这种行为是正常的还是我错过了什么?如果我是,有没有办法绕过它?

【问题讨论】:

  • 不相关:reduce() 可能会导致与 functools.reduce() 混淆。 reduce() 是 Python 2 中的内置函数。

标签: python multiprocessing python-multiprocessing


【解决方案1】:

它的行为应如此:lines == (1, {"foo": "bar"}) 即,linesdataset 列表中的一个项目——它不是列表本身。 pool.map() 在这方面表现得就像一张普通的地图:

squares = list(map(lambda item: item*item, [1, 2, 3]))
# -> [1, 4, 9]

【讨论】:

  • 谢谢!但是我不知道如何像在reduce之外(即调用数据集[0]时)那样访问数据。你知道方法吗?
  • 哦,我明白了!如果我以这种方式更改我的 reduce 函数: def reduce(lines): print(lines) print("break") 我将在每行之间得到“break”这个词。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-07-17
  • 2015-10-04
  • 1970-01-01
  • 1970-01-01
  • 2016-02-23
  • 2019-06-12
  • 1970-01-01
相关资源
最近更新 更多