生成 0 到 9 之间的随机整数
如何在Python中生成0
和9
(含)之间的随机整数?
例如,0
、1
、2
、3
、4
、>5
、6
、7
、8
、9
How can I generate random integers between 0
and 9
(inclusive) in Python?
For example, 0
, 1
, 2
, 3
, 4
, 5
, 6
, 7
, 8
, 9
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(23)
尝试
random.randrange
:Try
random.randrange
:尝试
random.randint
:文档状态:
Try
random.randint
:Docs state:
试试这个:
Try this:
这会生成 10 个介于 0 到 9 之间的伪随机整数。
This generates 10 pseudorandom integers in range 0 to 9 inclusive.
secrets
模块是新的Python 3.6。这比random
更好用于加密或安全用途的模块。要随机打印 0-9 范围内的整数:
有关详细信息,请参阅 PEP 506< /a>.
请注意,这实际上取决于用例。使用
random
模块,您可以设置随机种子,这对于伪随机但可重现的结果很有用,而使用secrets
模块则无法做到这一点。random
模块也更快(在 Python 3.9 上测试):The
secrets
module is new in Python 3.6. This is better than therandom
module for cryptography or security uses.To randomly print an integer in the inclusive range 0-9:
For details, see PEP 506.
Note that it really depends on the use case. With the
random
module you can set a random seed, useful for pseudorandom but reproducible results, and this is not possible with thesecrets
module.random
module is also faster (tested on Python 3.9):我会尝试以下其中一项:
1.> numpy.random.randint
2.> numpy.random.uniform
3.> numpy.random.choice
4.> random.randrange
5.> ; random.randint
速度:
► np.random.uniform 和 np.random.randint 比 np.random.choice、random.randrange、random 快得多(大约快 10 倍)。兰特。
注释:
I would try one of the following:
1.> numpy.random.randint
2.> numpy.random.uniform
3.> numpy.random.choice
4.> random.randrange
5.> random.randint
Speed:
► np.random.uniform and np.random.randint are much faster (~10 times faster) than np.random.choice, random.randrange, random.randint .
Notes:
选择数组的大小(在本例中,我选择的大小为 20)。然后,使用以下内容:
您可以期望看到以下形式的输出(每次运行时都会返回不同的随机整数;因此您可以期望输出数组中的整数与给定的示例不同下面)。
Choose the size of the array (in this example, I have chosen the size to be 20). And then, use the following:
You can expect to see an output of the following form (different random integers will be returned each time you run it; hence you can expect the integers in the output array to differ from the example given below).
虽然许多帖子演示了如何获取一个随机整数,但最初的问题是如何生成随机整数s(复数):
为了清楚起见,这里我们演示如何获取多个随机整数。
给定
代码
多个随机整数
随机整数样本
详细信息
一些帖子演示了如何本机生成多个随机整数。1以下是解决隐含问题的一些选项:
random.random
返回[0.0, 1.0)
B 范围内的随机浮点数random.randint
返回一个随机整数N
,使得a <= N <= b
random.randrange
是randint(a, b+1)
random.shuffle
随机排列一个序列random.choice
返回一个随机元素非空序列random.choices
返回总体中的k
个选择(带替换,Python 3.6+)random.sample
返回k
个唯一选择总体(无替换):2另请参阅 R. Hettinger 的演讲使用
random
模块中的示例来了解分块和别名。以下是标准库和 Numpy 中一些随机函数的比较:
您还可以快速转换许多 Numpy 中对随机整数样本的分布。3
示例
1< /sup>即@John Lawrence Aspden、@ST Mohammed、@SiddTheKid、@user14372、@zangw 等人
2@prashanth 提到此模块显示一个整数。
3由@Siddharth Satpathy演示
While many posts demonstrate how to get one random integer, the original question asks how to generate random integers (plural):
For clarity, here we demonstrate how to get multiple random integers.
Given
Code
Multiple, Random Integers
Sample of Random Integers
Details
Some posts demonstrate how to natively generate multiple random integers.1 Here are some options that address the implied question:
random.random
returns a random float in the range[0.0, 1.0)
random.randint
returns a random integerN
such thata <= N <= b
random.randrange
alias torandint(a, b+1)
random.shuffle
shuffles a sequence in placerandom.choice
returns a random element from the non-empty sequencerandom.choices
returnsk
selections from a population (with replacement, Python 3.6+)random.sample
returnsk
unique selections from a population (without replacement):2See also R. Hettinger's talk on Chunking and Aliasing using examples from the
random
module.Here is a comparison of some random functions in the Standard Library and Numpy:
You can also quickly convert one of many distributions in Numpy to a sample of random integers.3
Examples
1Namely @John Lawrence Aspden, @S T Mohammed, @SiddTheKid, @user14372, @zangw, et al.
2@prashanth mentions this module showing one integer.
3Demonstrated by @Siddharth Satpathy
您需要
random
python 模块,它是标准库的一部分。使用代码...
这会将变量
num1
设置为0
和9
之间的随机数(含)。You need the
random
python module which is part of your standard library.Use the code...
This will set the variable
num1
to a random number between0
and9
inclusive.通过 random.shuffle 尝试一下
Try this through
random.shuffle
如果是连续数字
randint
或 < a href="https://docs.python.org/library/random.html#random.randrange" rel="noreferrer">randrange
可能是最好的选择,但如果您序列中有几个不同的值(即list
),您也可以使用choice
:choice
也适用于不连续样本中的一项:如果您需要它“加密强度高”,还有一个
secrets.choice
在 python 3.6 及更高版本中:In case of continuous numbers
randint
orrandrange
are probably the best choices but if you have several distinct values in a sequence (i.e. alist
) you could also usechoice
:choice
also works for one item from a not-continuous sample:If you need it "cryptographically strong" there's also a
secrets.choice
in python 3.6 and newer:如果你想使用 numpy 那么使用以下命令:
if you want to use numpy then use the following:
要获取十个样本的列表:
To get a list of ten samples:
您可以尝试从 Python 导入 random 模块,然后让它在九个数字中进行选择。这真的很基本。
如果稍后要使用计算机选择的值,则可以尝试将其放入变量中,但如果不使用,则打印函数应按如下方式工作:
You can try importing the random module from Python and then making it choose a choice between the nine numbers. It's really basic.
You can try putting the value the computer chose in a variable if you're going to use it later, but if not, the print function should work as such:
生成 0 到 9 之间的随机整数。
输出:
Generating random integers between 0 and 9.
Output:
最好的方法是使用 import Random 函数
或不导入任何库:
这里 popitems 从字典
n
中删除并返回任意值。Best way is to use import Random function
or without any library import:
here the popitems removes and returns an arbitrary value from the dictionary
n
.random.sample
是另一个可以使用的random.sample
is another that can be used这更像是一种数学方法,但它 100% 有效:
假设您想使用 random.random() 函数生成
a
和a
之间的数字。代码>b。要实现此目的,只需执行以下操作:num = (ba)*random.random() + a;
当然,您可以生成更多数字。
This is more of a mathematical approach but it works 100% of the time:
Let's say you want to use
random.random()
function to generate a number betweena
andb
. To achieve this, just do the following:num = (b-a)*random.random() + a;
Of course, you can generate more numbers.
从 random 模块的文档页面:
random.SystemRandom,在Python 2.4 被认为是加密安全。它在撰写本文时最新的 Python 3.7.1 中仍然可用。
除了
string.digits
之外,还可以使用range
来代替其他一些答案,或许还可以进行理解。根据您的需要混合搭配。From the documentation page for the random module:
random.SystemRandom, which was introduced in Python 2.4, is considered cryptographically secure. It is still available in Python 3.7.1 which is current at time of writing.
Instead of
string.digits
,range
could be used per some of the other answers along perhaps with a comprehension. Mix and match according to your needs.我想我应该用
quantumrand
添加这些答案,它使用 ANU 的量子数生成器。不幸的是,这需要互联网连接,但如果您关心数字的“随机性”,那么这可能很有用。https://pypi.org/project/quantumrand/
示例
输出:
4
文档有很多不同的示例,包括掷骰子和列表选择器。
I thought I'd add to these answers with
quantumrand
, which uses ANU's quantum number generator. Unfortunately this requires an internet connection, but if you're concerned with "how random" the numbers are then this could be useful.https://pypi.org/project/quantumrand/
Example
Output:
4
The docs have a lot of different examples including dice rolls and a list picker.
对于 Python 3.6,我的运气更好,
只需添加 'ABCD' 和 'abcd' 或 '^!~=-><' 等字符要更改要从中提取的字符池,请更改范围以更改生成的字符数。
I had better luck with this for Python 3.6
Just add characters like 'ABCD' and 'abcd' or '^!~=-><' to alter the character pool to pull from, change the range to alter the number of characters generated.
OpenTURNS 不仅允许模拟随机整数,还可以使用 UserDefined 定义的类来定义关联的分布。
下面模拟了 12 个分布结果。
打印结果:
括号之所以存在,是因为
x
是一维中的Point
。在一次调用
getSample
中生成 12 个结果会更容易:将产生:
有关此主题的更多详细信息如下:http://openturns.github.io/openturns/master/user_manual/_ generated/openturns.UserDefined.html
OpenTURNS allows to not only simulate the random integers but also to define the associated distribution with the
UserDefined
defined class.The following simulates 12 outcomes of the distribution.
This prints:
The brackets are there because
x
is aPoint
in 1-dimension.It would be easier to generate the 12 outcomes in a single call to
getSample
:would produce:
More details on this topic are here: http://openturns.github.io/openturns/master/user_manual/_generated/openturns.UserDefined.html
使用
numpy
如果您可以接受 numpy 依赖项,那么从版本 1.17 开始,numpy 具有 生成器,如果你想的话,它比
randint
/choice
等快得多生成很多随机整数(例如超过10000个整数)。要构造它,请使用np.random.default_rng()
。然后,要生成随机整数,请调用integers()
或choice()
。如果要生成大量随机数列表(例如生成 100 万个随机整数,numpy 生成器比 numpy 的randint
快约 3 倍,约快 40 倍),它比标准库快得多比 stdlib 的随机
1)。例如,要生成 100 万个 0 到 9 之间的整数,可以使用以下任一方法。
默认使用PCG64生成器;但是,如果您想使用标准库中随机使用的 Mersenne Twister 生成器,那么您可以将其实例作为种子序列传递给 default_rng() ,如下所示接下来。
使用
random
如果您仅限于标准库,并且想要生成大量随机整数,那么
random.choices()
比快得多random.randint()
或random.randrange()
.2 例如,生成 0 到 9 之间的 100 万个随机整数:一些计时结果1
在 Python 3.12 和 numpy 1.26 上测试。
2 如果我们查看它们的源实现,
random.randrange()
(和random.randint()
因为它是前者的语法糖)使用 while 循环生成伪-随机数通过_randbelow 方法
,而
random.choices()
调用random()
一次并将其用于 对总体进行索引。因此,如果需要生成大量伪随机数,则该 while 循环的成本就会增加。With
numpy
If you're OK with having a numpy dependency, then since version 1.17, numpy has Generators, which are much faster than
randint
/choice
etc. if you want to generate a lot of random integers (e.g. more than 10000 integers). To construct it, usenp.random.default_rng()
. Then to generate random integers, callintegers()
orchoice()
. It is much faster than the standard library if you want to generate a large list of random numbers (e.g. to generate 1 million random integers, numpy generators are about 3 times faster than numpy'srandint
and about 40 times faster than stdlib'srandom
1).For example, to generate 1 million integers between 0 and 9, either of the following could be used.
By default, it uses PCG64 generator; however, if you want to use the Mersenne Twister generator which is used in
random
in the standard library, then you could pass its instance as a seeding sequence todefault_rng()
as follows.With
random
If you're restricted to the standard library, and you want to generate a lot of random integers, then
random.choices()
is much faster thanrandom.randint()
orrandom.randrange()
.2 For example to generate 1 million random integers between 0 and 9:Some timing results1
Tested on Python 3.12 and numpy 1.26.
2 If we look at their source implementations,
random.randrange()
(andrandom.randint()
because it is the former's syntactic sugar) use a while-loop to generate a pseudo-random number via_randbelow
method whilerandom.choices()
callsrandom()
once and uses it to index the population. So if a lot of pseudo-random numbers need to be generated, the cost of this while-loop adds up.