python随机数

In this tutorial, we are going to learn about Python Random Number. In our previous tutorial, we learned about Python math module.

在本教程中,我们将学习Python随机数。 在上一教程中,我们了解了Python数学模块 。

(Python Random Number)

To work with python random number, we need to import Python’s random module at first. Python random module provides pseudo-randomness.

要使用python随机数,我们首先需要导入Python的random模块。 Python随机模块提供伪随机性。





Python random module uses Mersenne Twister as the core random generator. So, this module is completely unsuitable for cryptographic purposes for being deterministic. However, we can use Python’s random module for most of the cases because Python’s random module contains many well known random distributions.

Python随机模块使用Mersenne Twister作为核心随机生成器。 因此,该模块完全不适合用于确定性的加密目的。 但是,在大多数情况下,我们可以使用Python的随机模块,因为Python的随机模块包含许多众所周知的随机分布。

(Python Random Integer)

In this section, we will be discussing about generation integer numbers randomly. We can use randint(a,b) function to get a random integer from range a to b. Again, we can get number from a sequence by using randrange(start, stop, step) function. Let’s see an example to get python random integer.

在本节中,我们将随机讨论生成整数。 我们可以使用randint(a,b)函数来获取范围从ab的随机整数。 同样,我们可以使用randrange(start, stop, step)函数从序列中获取数字。 让我们看一个获取python随机整数的示例。

import random as rand

a = 10
b = 100
print('\na =', a, 'and b =', b)
print('printing number [', a, ', ', b, ') :', rand.randint(a,b))

start = 1
stop = 12
step = 2
print('\nsequence = [1, 3, 5, 7, 9, 11]')
print('printing one number from the sequence :', rand.randrange(start, stop, step))

For each run, the output will change. However, here given a sample output.

对于每次运行,输出都会改变。 但是,这里给出了示例输出。





(Python Random Float)

There are several functions that returns real number or float randomly. For example, random() function returns a real number from 0 to 1 (exclusive).

有几个函数可以返回实数或随机浮动。 例如, random()函数返回一个从0到1(不包括)的实数。

Again, uniform(a, b) functions return a real number from a to b. Moreover there are some random distributions also available in Python random module. We can also get real number from those distribution.

同样, uniform(a, b)函数将实数从a返回到b。 此外,Python随机模块中还提供了一些随机分布。 我们还可以从这些分布中获得实数。

We can get random numbers from exponential distribution by using expovariate(lambd) function.

我们可以使用expovariate(lambd)函数从指数分布中获得随机数。





import random as rand

print('Random number from 0 to 1 :', rand.random())
print('Uniform Distribution [1,5] :', rand.uniform(1, 5))
print('Gaussian Distribution mu=0, sigma=1 :', rand.gauss(0, 1))
print('Exponential Distribution lambda = 1/10 :', rand.expovariate(1/10))

The values in output will vary for each execution. You will get output like this.

输出中的值对于每次执行都会有所不同。 您将获得这样的输出。

Random number from 0 to 1 : 0.5311529501408693
Uniform Distribution [1,5] : 3.8716411264052546
Gaussian Distribution mu=0, sigma=1 : 0.8779046620056893
Exponential Distribution lambda = 1/10 : 1.4637113187536595

(Python Random seed)

Python random number generation is based on the previous number, so using system time is a great way to ensure that every time our program runs, it generates different numbers.

Python随机数的生成基于先前的数字,因此使用系统时间是确保每次程序运行时都会生成不同数字的好方法。

We can use python random seed() function to set the initial value. Note that if our seed value doesn’t change in each execution, we will get same sequence of numbers. Below is a sample program to prove this theory about seed value.

我们可以使用python random seed()函数来设置初始值。 请注意,如果我们的种子值在每次执行中都没有改变,我们将获得相同的数字序列。 下面是一个示例程序,用于证明有关种子价值的这一理论。

import random

random.seed(10)

print('1st random number = ', random.random())
print('2nd random number = ', random.random())
print('1st random int = ', random.randint(1, 100))
print('2nd random int = ', random.randint(1, 100))

# resetting the seed to 10 i.e. first value
random.seed(10)

print('3rd random number = ', random.random())
print('4th random number = ', random.random())
print('3rd random int = ', random.randint(1, 100))
print('4th random int = ', random.randint(1, 100))

Below image shows the output produced by the python random seed example program. We will get the same sequence of random numbers for each run.





下图显示了python随机种子示例程序产生的输出。 对于每次运行,我们将获得相同的随机数序列。

(Python Random List – choice(), shuffle(), sample())

There are some functions to use randomness in a sequence. For example, using choice() function you can get a random element from a sequence.

有一些函数可以在序列中使用随机性。 例如,使用choice()函数可以从序列中获取随机元素。

Again, using shuffle() function you can shuffle the elements in a sequence.

同样,使用shuffle()函数可以将序列中的元素随机播放。

Also, using sample() function you can get x number of elements from a sequence randomly. So, let’s see the following code for random list example.

另外,使用sample()函数可以从序列中随机获取x个元素。 因此,让我们看下面的随机列表示例代码。

import random as rand

# initialize sequences
string = "inconvenience"
l = [1, 2, 3, 4, 10, 15]

# get a single element randomly
print('Single character randomly chosen :', rand.choice(string))
print('one randomly chosen number :', rand.choice(l))

# get multiple element
print('Randomly chosen 4 character from string :', rand.sample(string, 4))
print('Randomly chosen 4 length list :', rand.sample(l, 4))

# shuffle the list
rand.shuffle(l)
print('list is shuffled :', l)  # print the list

You may get output like the following.

您可能会得到类似以下的输出。

Single character randomly chosen : i
one randomly chosen number : 10
Randomly chosen 4 character from string : ['e', 'c', 'n', 'n']
Randomly chosen 4 length list : [2, 10, 3, 15]
list is shuffled : [2, 4, 15, 3, 10, 1]

So, that’s all for python random number. To know more, see their official documentation.

所以,这就是python随机数的全部。 要了解更多信息,请参阅其官方文档