传递给 Pool 映射函数时迭代 dict.items() 会产生奇怪的结果
Iterating dict.items() when passed to Pool map function gives weird results
我正在尝试在 Python 3 中进行一些多处理。当我尝试遍历从多处理模块通过 Pool.map() 方法传递的字典项时,我发现了一些奇怪的东西。
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
这种行为是正常的还是我遗漏了什么?如果我是,有没有办法绕过它?
它的行为应该是这样的:lines == (1, {"foo": "bar"})
即,lines
是 dataset
列表中的一个 item -- 它不是列出自己。 pool.map()
在这方面表现得像普通地图:
squares = list(map(lambda item: item*item, [1, 2, 3]))
# -> [1, 4, 9]
我正在尝试在 Python 3 中进行一些多处理。当我尝试遍历从多处理模块通过 Pool.map() 方法传递的字典项时,我发现了一些奇怪的东西。
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
这种行为是正常的还是我遗漏了什么?如果我是,有没有办法绕过它?
它的行为应该是这样的:lines == (1, {"foo": "bar"})
即,lines
是 dataset
列表中的一个 item -- 它不是列出自己。 pool.map()
在这方面表现得像普通地图:
squares = list(map(lambda item: item*item, [1, 2, 3]))
# -> [1, 4, 9]