gpt4 book ai didi

python - python map reduce与云计算map/reduce的关系?

转载 作者:太空狗 更新时间:2023-10-29 22:20:06 24 4
gpt4 key购买 nike

我是 Python 新手,

有人知道 Python(和函数式语言)函数 map()/reduce() 和与分布式计算相关的 MapReduce 概念之间的关系吗?

最佳答案

map/reduce 的云概念非常相似,但改为并行工作。首先,每个数据对象都通过一个函数传递,该函数将其映射到一个新对象(通常是某种字典)。然后,对 map 返回的成对对象调用 reduce 函数,直到只剩下一个。这就是 map/reduce 操作的结果。

一个重要的考虑因素是,由于并行化,reduce 函数必须能够接收来自 map 函数的对象以及来自先前 的对象>减少功能。当您考虑并行化如何进行时,这更有意义。许多机器各自将其数据缩减为单个对象,然后这些对象将缩减为最终输出。当然,如果数据很多,这可能发生在不止一层。

这是一个简单的示例,说明您可以如何使用 map/reduce 框架对列表中的单词进行计数:

list = ['a', 'foo', 'bar', 'foobar', 'foo', 'a', 'bar', 'bar', 'bar', 'bar', 'foo']
list2 = ['b', 'foo', 'foo', 'b', 'a', 'bar']

map 函数看起来像这样:

def wordToDict(word):
return {word: 1}

reduce 函数看起来像这样:

def countReduce(d1, d2):
out = d1.copy()
for key in d2:
if key in out:
out[key] += d2[key]
else:
out[key] = d2[key]
return out

然后你可以这样映射/归约:

reduce(countReduce, map(wordToDict, list + list2))

>>> {'a': 3, 'foobar': 1, 'b': 2, 'bar': 6, 'foo': 5}

但您也可以这样做(并行化会这样做):

reduce(countReduce, [reduce(countReduce, map(wordToDict, list)), reduce(countReduce, map(wordToDict, list2))])

>>> {'a': 3, 'foobar': 1, 'b': 2, 'foo': 5, 'bar': 6}

关于python - python map reduce与云计算map/reduce的关系?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8117515/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com