Generate a set of sorted random numbers from a specific range

前端 未结 2 881
孤独总比滥情好
孤独总比滥情好 2020-12-20 20:35

I\'d like to generate a set of x unique random numbers and sort them in Python. For example: range(1000, 10000) x = 100

I\'ve figured out to import random and use the

2条回答
  •  清酒与你
    2020-12-20 21:08

    more_itertools implements the random_combinations itertools recipe, which returns r sorted random numbers, if given a sorted input.

    import more_itertools as mit
    
    mit.random_combination(range(1000, 10000), r=100)
    # (1016, 1112, 1233, 1367, 1446, 1460, 1518, 1807, 1832, 1956, ...)
    

    This is unlike random.sample, which returns an unsorted result.


    Details

    Looking at the recipe, we can see 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 inherently sorted and becomes the pool from which random elements are selected. Although the indices are randomly selected, they are later sorted. Since the pool and indices are both sorted, the results are also sorted.

    In summary, this does the same as @Volatility's answer, except the sorting is handled for you.

    Cavaet: random_combinations requires the length of the iterable to exceed the value of r, otherwise an error is raised.

提交回复
热议问题