我在Pyspark中有两个RDD,其中包含如下嵌套元素:
a = sc.parallelize(( (1,2), 3,(4,(6,7,(8,9,(11),10)),5,12)))
b = sc.parallelize(1,2,(3,4))
嵌套可以有任何深度
我想合并它们,然后找到任意深度的最大元素,所以我尝试将其转换为RDD,而不使用这样的嵌套值(1,2,3,4,6,7,8,9,11,10,5,12,1,2,3,4),并使用其中任何一个(map,reduce,filter,flatmap,lamda函数)获得最大值。谁能告诉我如何变换或获得最大元素
我提出了一个解决方案,但它只适用于两个深度级别,如
a = sc.parallelize(( (1,2), 3,(4,5)))
b = sc.parallelize((2,(4,6,7),8))
def maxReduce(tup):
return int(functools.reduce(lambda a,b : a if a>b else b, tup))
maxFunc = lambda x: maxReduce(x) if type(x) == tuple else x
a.union(b).map(lambda x: maxFunc(x)).reduce(lambda a,b : a if a>b else b)
上面的代码只适用于深度2,我需要为任何给定的深度(1,(2,3,(4,5,(6,(7,(8))))))
使用它
听起来是递归函数的一个很好的用例:
相关问题 更多 >
编程相关推荐