在使用Reduce这个函数需要特别注意的一点是,reduce必须要求输入与输出是相同类型,例如:
>>> rddx = sc.parallelize([('a',1),('b',2),('c',5)])
>>> rddx.reduce(lambda x,y:x[1]+y[1]) #报错
TypeError: 'int' object has no attribute '__getitem__'
>>> rddx.reduce(lambda x,y:(x[0],x[1]+y[1]))
('a', 8)
官网上对reduce这个函数的描述是:Reduces the elements of this RDD using the specified commutative and associative binary operator。
代码
>>> rddx.reduce(lambda x,y:x[1]+y[1])
报错的原因在于,当第一次(‘a’,1)和(‘b’,2)应用到lambda函数时,返回值是3。所以在下一次reduce时,lambda的输入是 x=3, y=(‘c’,5),抛出TypeError异常。
而代码
>>> rddx.reduce(lambda x,y:(x[0],x[1]+y[1]))
把(‘a’,1)和(‘b’,2)作为lambda函数的输入,返回值是(‘a’,3)。所以在下一次reduce时,lambda的输入是 x=(‘a’,3), y=(‘c’,5),最终返回(‘a’, 8)。
本文详细解析了在Spark中使用Reduce函数的注意事项,通过实例展示了如何确保输入与输出类型的匹配,避免运行时错误。
5万+

被折叠的 条评论
为什么被折叠?



