Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

python - Unique only cartesian product of several lists

The following works well for cart_product([1,2,3], [a,b,c], [v]), doesn't it also return duplicate cartesian product, if so, how to get unique cartesian products?

import itertools
def cart_product(*somelists):
    for element in itertools.product(*somelists):
        print element

also this doesn't seem to work when I pass in a list containing lists [ [1,2,3],[a,b,c],[v] ]

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)
  1. To get only the unique elements, you can use set notation like this (Note: This doesnt guarantee the order)

    return list({element for element in itertools.product(*somelists)})
    

    or as per Paul Draper's comment we can do it like this

    list(set(itertools.product(*somelists)))
    

    If you want to maintain the order as well

    import itertools
    def cart_product(somelists):
        result, tempSet = [], set()
        for element in itertools.product(*somelists):
            if element not in tempSet:
            tempSet.add(element)
            result.append(element)
        return result
    
  2. To make your program work with list of lists, just change the function declaration from

    def cart_product(*somelists):
    

    to

    def cart_product(somelists):
    

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...