Skip to content Skip to sidebar Skip to footer

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

Solution 1:

  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
    defcart_product(somelists):
        result, tempSet = [], set()
        for element in itertools.product(*somelists):
            if element notin 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

    defcart_product(*somelists):
    

    to

    defcart_product(somelists):
    

Post a Comment for "Unique Only Cartesian Product Of Several Lists"