I'm trying to figure out the most efficient way to get a sorted list of combinations of the items of multiple lists (the number is not known beforehand) in Python (3). For example, if I have a list of sublists:
a = [[0, 1, 2], [0], [0, 1]]
I expect the following output:
[(0, 0, 0), (0, 0, 1), (0, 0, 2), (0, 1, 1), (0, 1, 2)]
At the moment, the best method I have is to use itertools.product()
to first generate all possible permutations of the three lists, sort the contents of the permutations, then take the set of those items, and then to finally sort that set:
tuples = it.product(*a)
tuples_sorted = [tuple(sorted(i)) for i in tuples]
output = sorted(set(tuples_sorted))
This works just fine, but I was wondering if there was a more efficient or built-in way of doing this? I can imagine the multiple sorting steps getting really cumbersome for a large number of sublists, or for really long sublists. I'm open to numpy solutions, too.