Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
197 views
in Technique[技术] by (71.8m points)

python - How can i get a Cartesian product filtering out the pair of tuples with repeated results?

Im trying to define a function that gets the cartesian product of a given list with itself , however i nedd to filter out the elemnts that contains the same pairs.

For example: Getting the cartesian product of rdd and fiter out the results ((1,0),(1,0)),((2,0),(2,0)) and ((3,0),(3,0))

rdd = sc.parallelize([(1,0), (2,0), (3,0)])


def get_cart(rdd):
   
    a=sorted(rdd.cartesian(rdd).collect()) 
    aRDD=sc.parallelize(a)
 
    return aRDD

Im expecting to get the output:

[((1, 0), (2, 0)), ((1, 0), (3, 0)), ((2, 0), (1, 0)), ((2, 0), (3, 0)), ((3, 0), (1, 0)), ((3, 0), (2, 0))]

Instead im getting:

[((1, 0), (1, 0)),
 ((1, 0), (2, 0)),
 ((1, 0), (3, 0)),
 ((2, 0), (1, 0)),
 ((2, 0), (2, 0)),
 ((2, 0), (3, 0)),
 ((3, 0), (1, 0)),
 ((3, 0), (2, 0)),
 ((3, 0), (3, 0))]
question from:https://stackoverflow.com/questions/65866091/how-can-i-get-a-cartesian-product-filtering-out-the-pair-of-tuples-with-repeated

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use a filter to remove RDD elements with the first tuple equal to the second tuple:

def get_cart(rdd):
    return rdd.cartesian(rdd).filter(lambda r: r[0] != r[1])

Note that there is no need to collect the RDD and re-parallelize it after cartesian, which already returns an RDD.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...