如何在RDD中求和列表的一部分 [英] How to Sum a part of a list in RDD
本文介绍了如何在RDD中求和列表的一部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个RDD,我想总结一下列表的一部分.
I have an RDD, and I would like to sum a part of the list.
(key, element2 + element3)
(1, List(2.0, 3.0, 4.0, 5.0)), (2, List(1.0, -1.0, -2.0, -3.0))
输出应如下所示,
(1, 7.0), (2, -3.0)
谢谢
推荐答案
您可以 map
并在第二部分建立索引:
You can map
and indexing on the second part:
yourRddOfTuples.map(tuple => {val list = tuple._2; list(1) + list(2)})
在评论后更新,将其转换为 Vector
:
Update after your comment, convert it to Vector
:
yourRddOfTuples.map(tuple => {val vs = tuple._2.toVector; vs(1) + vs(2)})
或者如果您不想使用转化:
Or if you do not want to use conversions:
yourRddOfTuples.map(_._2.drop(1).take(2).sum)
这会从元组( .map(_._ 2
))的第二个元素中跳过第一个元素( .drop(1)
),然后取下两个( .take(2)
)(如果您少于,则可以减少),然后将它们相加( .sum
).
This skips the first element (.drop(1)
) from the second element of the tuple (.map(_._2
), takes the next two (.take(2)
) (might be less if you have less) and sums them (.sum
).
这篇关于如何在RDD中求和列表的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文