I have a list of sets, and I wish to sample n different samples each containing an item from each set. What I do not want is to have it in order, so, for example, I will ge
You can use sample from the random lib:
import random
[[random.sample(x,1)[0] for x in list_of_sets] for _ in range(n)]
for example:
list_of_sets = [{1,2,3}, {4,5,6}, {1,4,7}]
n = 3
A possible output will be:
[[2, 4, 7], [1, 4, 7], [1, 6, 1]]
EDIT:
If we want to avoid repetitions we can use a while loop and collect the results to a set. In addition you can check that n is valid and return the Cartesian product for invalid n values:
chosen = set()
if 0 < n < reduce(lambda a,b: a*b,[len(x) for x in list_of_sets]):
while len(chosen) < n:
chosen.add(tuple([random.sample(x,1)[0] for x in list_of_sets]))
else:
chosen = itertools.product(*list_of_sets)