spark 的 map 和 flatMap 应该怎样理解?

2016-08-05 10:08:23 +08:00
 checgg
conf = SparkConf().setAppName("Simple App").setMaster("local")
sc = SparkContext(conf=conf)
file = "./README.md"
“”“
111 aaa bcd
22 qqq www
”“”
dataFile = sc.textFile(file)
test = dataFile.map(lambda s : s)
print test.collect() # [u'111 aaa bcd', u'22 qqq www']
test = dataFile.flatMap(lambda s : s)
print test.collect() # [u'1', u'1', u'1', u' ', u'a', u'a', u'a', u' ', u'b', u'c', u'd', u'2', u'2', u' ', u'q', u'q', u'q', u' ', u'w', u'w', u'w'


map 文档是这样解释的: Return a new distributed dataset formed by passing each element of the source through a function func.
我的理解是对 rdd 的每一个 element 进行 func,最后返回的数量应该是等于 element 的数量的。

flatMap 是这样解释:Similar to map, but each input item can be mapped to 0 or more output items (so func should return a Seq rather than a single item).

这里不懂为什么 flatMap 结果是一个个字母?
2383 次点击
所在节点    问与答
3 条回复
wayslog
2016-08-05 10:26:54 +08:00
很简单啊… map 是一对一转成其他的值, flatMap 是有可能一个值转成
wayslog
2016-08-05 10:27:39 +08:00
接上面,一个值转成了不限数量个值……
SoloCompany
2016-08-06 01:59:56 +08:00
map 是一阶函数转换,比如 a -> a.name
map 之后元素个数不变是 n -> n 变换

flatMap 是二阶函数转换,把树结构摊平,比如 a -> lambda (x -> x.children)
摊平之后的元素是遍历所有叶结点的结果, 可以近似看做 n -> n^2 变换

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/297289

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX