使⽤Pythonrandom模块⽣成随机数据实例
在本节中,我们将学习如何使⽤random模块(random)在Python中⽣成随机数和数据。该模块为各种分布(包括整数,浮点数(实数))实现了伪随机数⽣成器。
本⽂的⽬标:
以下是我们将在本⽂中介绍的常见操作的列表。
为各种分布⽣成随机数,包括整数和浮点数。
随机抽样并从总体中选择元素。
random模块的功能。
随机播放序列数据。播种随机⽣成器。
⽣成随机字符串和密码。
使⽤秘密模块的加密安全随机⽣成器。⽣成安全令牌,安全密钥和URL
如何设置随机发⽣器的状态。
使⽤NumPy的random⽣成随机数组。
使⽤UUID模块⽣成唯⼀ID
如何使⽤random模块
random模块具有各种功能来完成所有上述任务。我们将在本⽂的后半部分看到如何使⽤这些功能。
您需要在程序中导⼊random模块,然后就可以使⽤该模块了。使⽤以下语句将random模块导⼊代码中。
import random
现在让我们看看如何使⽤random模块。
import random
print("Printing random number using random.random()")
print(random.random())
如您所见,我们得到了0.50。您可能会得到其他号码。
random()是random模块的最基本功能。
random模块的⼏乎所有功能都依赖于基本功能random()。
random()返回范围为[0.0,1.0)的下⼀个随机浮点数。
random模块功能
现在,让我们看看random模块中可⽤的不同功能及其⽤法。
random.randint(a,b)
使⽤random.randint()⽣成⼀定范围内的随机整数。让我们看⼀下⽣成0到9之间的随机数的⽰例。
import random
print("Random integer is", random.randint(0, 9))
random.randrange(start, stop [, step])
此函数从中返回随机选择的整数range(start, stop, step)。使⽤此函数可⽣成范围内的随机整数。例如,random.randrange(2, 20, 2)将返回2到20之间的任意随机数,例如2、4、6,…18。
import random
print("Random integer is", random.randrange(2, 20, 2))
random.choice(q)
使⽤该random.choice功能从列表或任何序列中随机选择⼀个项⽬。
import random
city_list = ['New York', 'Los Angeles', 'Chicago', 'Houston', 'Philadelphia']
print("Random element from list:", random.choice(city_list))
random.sample(population, k)
要从列表或任何序列中随机选择多个元素时,请使⽤此功能。
import random
city_list = ['New York', 'Los Angeles', 'Chicago', 'Houston', 'Philadelphia']
print("Pick 2 Random element from list:", random.sample(city_list, 2))
random.choices()
random.choices(population, weights=None, *, cum_weights=None, k=1)
如果要从序列中随机选择多个元素,请使⽤此⽅法。在Python 3.6版中引⼊的Choices⽅法可以重复元素。这是带有替换的随机样本。import random
#sampling with replacement
list = [20, 30, 40, 50 ,60, 70, 80, 90]
sampling = random.choices(list, k=5)
print("sampling with choices method ", sampling)
将random.choices()主要⽤于实现加权随机选择,这样我们就可以选择不同的概率列表元素
random.ed(a=None, version=2)
carated函数⽤于初始化 Python中的伪随机数⽣成器。random模块使⽤种⼦值作为基础来⽣成随机数。如果不存在种⼦值,则需要系统当前时间。如果在调⽤任何random模块函数之前使⽤相同的种⼦值,则每次都会获得相同的输出。
import random
# Random number with ed 6
random.ed(6)
print(random.randint(10, 20))
random.ed(6)
print(random.randint(10, 20))
random.shuffle(x [,random])
使⽤此功能可以随机排列或随机化列表或其他序列类型。该shuffle功能可就地随机播放列表。最常见的例⼦是洗牌。
list = [2,5,8,9,12]
random.shuffle(list)
print ("Printing shuffled list ", list)
random.uniform(开始,结束)
使⽤random.uniform()⽣成⼀定范围内的浮点数。
import random
print("floating point within given range")
print(random.uniform(10.5, 25.5))
hr是什么意思iangular(低,⾼,模式)
该iangular()函数返回⼀个随机浮点数N,使得lower <= N <= upper在这些边界之间具有指定的模式。
下限的默认值为零,上限为1。此外,peak参数默认为边界之间的中点,从⽽给出对称分布。
使⽤该iangular()函数⽣成⽤于三⾓分布的随机数,以在仿真中使⽤这些数。即从三⾓概率分布中产⽣值。
import random
print("floating point triangular")
iangular(10.5, 25.5, 5.5))
产⽣随机字串
在本节中,我将让您知道如何在python中⽣成固定长度的随机字符串。
本指南包括以下内容:–
yangtzeriver随机⽣成固定长度的字符串。
获取带有字母和数字的随机字母数字字符串。
⽣成包含字母,数字和特殊符号的随机密码。
Python中的加密安全随机⽣成器
由random模块⽣成的随机数和数据不是加密安全的。那么,如何⽣成在Python中具有加密安全性的随机数呢?
密码安全的伪随机数⽣成器是⼀个随机数⽣成器,它具有的特性使其适合在数据安全⾄关重要的密码学应⽤中使⽤。
所有加密安全的随机⽣成器函数均返回随机字节。
此函数返回的随机字节取决于操作系统的随机源。随机性的质量取决于操作系统的随机性来源。
我们可以使⽤以下⽅法以加密⽅式保护Python中的随机⽣成器
该秘密模块以固定随机数据
使⽤操作系统。urandom()
使⽤随机。SystemRandom类
import random
import crets
number = random.SystemRandom().random()
print("cure number is ", number)
print("Secure byte token", ken_bytes(16))
获取并设置随机发⽣器的状态
random模块具有两个函数getstate和tstate,这有助于我们捕获随机发⽣器的当前内部状态。使⽤此状态,我们可以⽣成相同的随机数或数据序列。
马耳他英文该getstate函数通过捕获随机⽣成器的当前内部状态来返回对象。我们可以将此状态传递给tstate⽅法,以将该状态恢复为当前状态。
注意:通过将状态更改为上⼀个状态,我们可以再次获得相同的随机数据。例如,如果您想再次获得相同的样本项⽬,则可以使⽤这些功能。
random.tstate(状态)
该tstate()函数将⽣成器的内部状态恢复为状态对象。即它再次应⽤相同的状态。可以通过调⽤该getstate函数来获取此状态对象。
为什么要使⽤getstate和tstate函数
如果获得了先前的状态并将其还原,则可以⼀次⼜⼀次地再现相同的随机数据。请记住,您不能使⽤其他随机函数,也不能更改参数值。这样,您正在更改状态。
现在让我们看⼀下⽰例,以清楚地了解如何在Python中获取和设置随机⽣成器。
import random
number_list = [3, 6, 9, 12, 15, 18, 21, 24, 27, 30]
print("First Sample is ", random.sample(number_list,k=5))
state = state() # store this current state in state object
print("Second Sample is ", random.sample(number_list,k=5))
random.tstate(state) # restore state now using tstate
print("Third Sample is ", random.sample(number_list,k=5)) #Now it will print the same cond sample list
random.tstate(state) # restore state now
print("Fourth Sample is ", random.sample(number_list,k=5)) #again it will print the same cond sample list again
如您在输出中看到的,由于重置了随机⽣成器,我们得到了相同的样本列表。
Numpy.random –数组的PRNG
PRNG是伪随机数⽣成器的⾸字母缩写。如您所知,使⽤Pythonrandom模块,我们可以⽣成标量随机数和数据。
每当您要⽣成随机数数组时,都需要使⽤numpy.random。
numpy提供了numpy.random具有多种功能的软件包,可以为各种分布⽣成随机的n维数组。
现在,让我们看⼀些例⼦。
⽣成⼀个随机的n维浮点数数组
esq
使⽤numpy.random.rand()产⽣随机浮点数的在范围内的n维阵列[0.0,1.0)
使⽤numpy.random.uniform产⽣随机浮点数的在[低的范围内的n维阵列中,⾼)
import numpy
random_float_array = numpy.random.rand(2, 2)
print("2 X 2 random float array in [0.0, 1.0] \n", random_float_array,"\n")
random_float_array = numpy.random.uniform(25.5, 99.5, size=(3, 2))
print("3 X 2 random float array in range [25.5, 99.5] \n", random_float_array,"\n")
⽣成整数的随机n维数组
使⽤numpy.random.random_integers()⽣成随机的n维整数数组。
import numpy
random_integer_array = numpy.random.random_integers(1, 10, 5)
print("1-dimensional random integer array \n", random_integer_array,"\n")
random_integer_array = numpy.random.random_integers(1, 10, size=(3, 2))
print("2-dimensional random integer array \n", random_integer_array)
从数字或序列数组中选择随机元素
使⽤numpy.random.choice()⽣成随机样本。
使⽤此⽅法可以从n维数组中获取单个或多个随机数,⽆论替换与否。
现在来看⽰例。
import numpy
社交礼仪与口才培训array =[10, 20, 30, 40, 50, 20, 40]
single_random_choice = numpy.random.choice(array, size=1)
print("single random choice from 1-D array", single_random_choice)
multiple_random_choice = numpy.random.choice(array, size=3, replace=Fal)
print("multiple random choice from 1-D array without replacement ", multiple_random_choice)
multiple_random_choice = numpy.random.choice(array, size=3, replace=True)
print("multiple random choice from 1-D array with replacement ", multiple_random_choice)
我们将在后续⽂章中介绍其他numpy的随机包函数及其⽤法。
⽣成随机的通⽤唯⼀ID
Python UUID模块提供了不变的UUID对象。 UUID是通⽤唯⼀标识符。
它具有⽣成所有版本的UUID的功能。使⽤uuid.uuid4()函数,您可以⽣成128位长的随机唯⼀ID⼴告,这种⼴告在密码学上是安全的。这些唯⼀的ID⽤于标识计算机系统中的⽂档,⽤户,资源或任何信息。
范例:
import uuid
剑桥青少
# get a random UUID
safeId = uuid.uuid4()
print("safe unique id is ", safeId)
使⽤random模块的骰⼦游戏
我创建了⼀个简单的骰⼦游戏,以了解random模块的功能。在这个游戏中,我们有两个玩家和两个骰⼦。
每个玩家⼀个⼀个地洗牌,⼀个都洗牌。fci
该算法计算两个骰⼦数的总和,并将其添加到每个玩家的计分板上。
得分⾼的玩家是赢家。
程序:
import random因为英语
PlayerOne = "Eric"
PlayerTwo = "Kelly"
EricScore = 0
KellyScore = 0
# each dice contains six numbers
diceOne = [1, 2, 3, 4, 5, 6]
diceTwo = [1, 2, 3, 4, 5, 6]
def playDiceGame():
"""#Both Eric and Kelly will roll both the dices using shuffle method"""
for i in range(5):
#shuffle both the dice 5 times
random.shuffle(diceOne)
random.shuffle(diceTwo)
firstNumber = random.choice(diceOne) # u choice method to pick one number randomly
SecondNumber = random.choice(diceTwo)
return firstNumber + SecondNumber
print("Dice game using a random module\n")
#Let's play Dice game three times
for i in range(3):
# let's do toss to determine who has the right to play first
EricTossNumber = random.randint(1, 100) # generate random number from 1 to 100. including 100
KellyTossNumber = random.randrange(1, 101, 1) # generate random number from 1 to 100. don't including 101
if( EricTossNumber > KellyTossNumber):
print("Eric won the toss")
EricScore = playDiceGame()
圣诞英文KellyScore = playDiceGame()
el:
print("Kelly won the toss")
KellyScore = playDiceGame()
EricScore = playDiceGame()
if(EricScore > KellyScore):
print ("Eric is winner of dice game. Eric's Score is:", EricScore, "Kelly's score is:", KellyScore, "\n")
el:
print("Kelly is winner of dice game. Kelly's Score is:", KellyScore, "Eric's score is:", EricScore, "\n")
后继将会有更多⽂章使⽤实例⽅式介绍python的随机模块random和其它能帮助我们⽣成随机数据的模块。