more_itertools implements random_combinations itertools recipe, which returns r sorted random numbers if a sorted input is given.
import more_itertools as mit mit.random_combination(range(1000, 10000), r=100)
Unlike random.sample , which returns an unsorted result.
More details
Looking at the recipe, we can understand why this order is established.
From itertools recipes :
def random_combination(iterable, r): """Return a random *r* length subsequence of the elements in *iterable*. >>> random_combination(range(5), 3) # doctest:+SKIP (2, 3, 4) This equivalent to taking a random selection from ``itertools.combinations(iterable, r)``. """ pool = tuple(iterable) n = len(pool) indices = sorted(sample(range(n), r)) return tuple(pool[i] for i in indices)
range() is essentially sorted and becomes a pool from which random elements are selected. Although indexes are randomly selected, they are subsequently sorted. Because pool and indices sorts are sorted, results are also sorted.
In general, this does the same as @Volatility's answer, except that sorting is handled for you.
Cavaet: random_combinations requires that the length of the iterability exceeds the value of r , otherwise an error occurs.
source share