You can implement the random_product
itertools recipe. I will use a third-party library, more_itertools
, that implements this recipe for us. Install this library via pip install more_itertools
.
Code
import more_itertool as mit
x, y, m = "abcdefgh", range(10), 2
iterable = mit.random_product(x, y, repeat=m)
Results
iterable
# ('e', 9, 'f', 3)
It is not clear in what form the OP wants the results, but you can group x
and y
together, e.g. [(x[0], y[0]), (x[1], y[1]), ...]
:
paired_xy = list(zip(*[iter(iterable)]*2))
paired_xy
# [('e', 9), ('f', 3)]
See also more_itertools.sliced
and more_itertools.grouper
for grouping consecutive items.
Alternatively, you may zip
further to group along x
and y
, e.g. [(x[0], x[1], ...), (y[0], y[1], ...)]
:
paired_xx = list(zip(*paired_xy))
paired_xx
# [('e', 'f'), (9, 3)]
Note, this approach accepts any number of iterables, x
, y
, z
, etc.
# Select m random items from multiples iterables, REF 101
x, y, m = "abcdefgh", range(10), 2
a, b, c = "ABCDE", range(10, 100, 10), [False, True]
iterable = mit.random_product(x, y, a, b, c, repeat=m)
iterable
# ('d', 6, 'E', 80, True, 'a', 1, 'D', 50, False)
Details
From the itertools recipes:
def random_product(*args, repeat=1):
"Random selection from itertools.product(*args, **kwds)"
pools = [tuple(pool) for pool in args] * repeat
return tuple(random.choice(pool) for pool in pools)
We can see the function indeed accepts multiple arguments which each become a collection of pools. The size of the pool scales by the value of repeat
keyword. A random selection is made from each pool and tupled together as the final result.
See also more_itertools
docs for more tools.