从特定范围生成一组排序的随机数 [英] Generate a set of sorted random numbers from a specific range

查看:99
本文介绍了从特定范围生成一组排序的随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想生成一组x个唯一的随机数,并用Python对其进行排序.例如: 范围(1000,10000) x = 100

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

我发现要导入random并使用random.randrange方法,然后循环获得100个随机数,最后对它们进行排序.

I've figured out to import random and use the random.randrange method, then loop to get 100 random numbers and in the end sort them.

但是,我不知道如何获得唯一的数字(这样就不会重复)-我应该验证每个循环吗?还是还有其他更简单的方法呢?我应该如何对它们进行排序?

However, I don't know how to get unique numbers (such that they do not repeat) - should I validate each and every loop? Or is there any other easier way how to do it? And how should I sort them?

谢谢大家!

推荐答案

使用 random.sample

numbers = random.sample(xrange(1000, 10000), 100)  # or `range` in Python 3

排序部分很容易-使用 list.sort 方法.

The sorting part is easy - use the list.sort method.

numbers.sort()

默认情况下,它将按从小到大的顺序对其进行排序,但是它采用一个可选的key参数来确定对其进行排序的方式.

By default this will sort it from smallest number to largest, but it takes an optional key argument which determines what to sort it on.

还有一个 sorted 函数,该函数不会在-位置,而是返回排序列表.

There is also a sorted function which doesn't modify a list in-place, but rather returns a sorted list.

numbers_sorted = sorted(numbers)

这还有一个可选的key参数.

This also has an optional key argument.

这篇关于从特定范围生成一组排序的随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆