Python随机数
在本教程中,我们将学习Python随机数。
Python随机数
要使用python随机数,我们首先需要导入Python的random模块。
Python随机模块提供伪随机性。
Python随机模块使用Mersenne Twister作为核心随机生成器。
因此,由于确定性,此模块完全不适合加密目的。
但是,在大多数情况下,我们可以使用Python的随机模块,因为Python的随机模块包含许多众所周知的随机分布。
Python随机整数
在本节中,我们将随机讨论生成整数。
我们可以使用randint(a,b)函数来获取范围从a到b的随机整数。
同样,我们可以使用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))
对于每次运行,输出都会改变。
但是,这里给出了示例输出。
Python随机浮动
有几个函数可以返回实数或者随机浮动。
例如,random()
函数返回一个从0到1(不包括)的实数。
同样,uniform(a,b)
函数将实数从a返回到b。
此外,Python随机模块中还提供了一些随机分布。
我们还可以从这些分布中获得实数。
我们可以使用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))
输出中的值对于每次执行都会有所不同。
您将得到这样的输出。
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随机种子
Python随机数的生成基于先前的数字,因此使用系统时间是确保每次程序运行时都会生成不同数字的好方法。
我们可以使用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))
下图显示了python random seed示例程序产生的输出。
对于每次运行,我们将获得相同的随机数序列。
Python随机列表– choice(),shuffle(),sample()
有一些函数可以在序列中使用随机性。
例如,使用choice()
函数,您可以从序列中获取随机元素。
同样,使用shuffle()
函数,您可以将序列中的元素进行混洗。
而且,使用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
您可能会得到类似以下的输出。
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]