今天小编就生成随机数,整理了多个方式,方便大家在项目时,根据自己的需求,直接拿来套用即可,以下内容相当详细,具体来看看吧~
说明:python中生成随机数主要用到random模块,方法主要包括:randint、uniform、random、sample、choice等几种常用方法;
环境:Mac OS 10.14.6/Windows10、python3.7.3
1、在[a, b]之间产生随机整数(randint方法)
代码演示:import random;
for i in range(2):
ret = random.randint(1000, 9999)
print(“在[a, b]之间产生随机整数:random.randint(1000, 9999)=”,ret)
运行结果:
2、[a, b]之间产生随机浮点数(uniform方法)
代码演示:import random;
for i in range(2):
ret = random.uniform(1.0, 100.0)
print(“在[a, b]之间产生随机浮点数:random.uniform(1.0, 100.0) = “,ret)
运行结果:
3、在[0.0, 1.0)之间产生随机浮点数(random方法)
代码演示:import random;
for i in range(2):
ret = random.random()
print(“在[0.0, 1.0)之间产生随机浮点数:random.random() = “,ret)
运行结果:
4、在样本samples中随机选择n个(sample方法)
代码演示:import random
samples = {“Mon”, “Tue”, “Wed”, “Thu”, “Fri”, “Sat”, “Sun” }
for i in range(2):
ret = random.sample(samples, 2)
print(“在样本samples中随机选择n个:random.sample(samples, 2) = “,ret)
运行结果:
5、在序列list1中随机选择1个(choice方法)
代码演示:import random
list1 = (“hello”, “world”, ‘we’, ‘are’, “learning”, “python”, ‘very’, ‘good’)
for i in range(2):
ret = random.choice(list1)
print(“在序列list1中随机选择1个:random.choice(list1) =”,ret)
运行结果:
6、随机生成唯一流水号(时间戳)
代码演示:import datetime;
import random;
for i in range (0,1):
nowTime=datetime.datetime.now().strftime(“%Y%m%d%H%M%S”)
randomNum=random.randint(0,99)
if randomNum<=10:
randomNum=str(0)+str(randomNum)
uniqueNum=str(nowTime)+str(randomNum)
print (“时间戳:”,uniqueNum)
7、随机生成验证码
代码演示:import random
def random_num():
code = ”
for i in range(4):
ran1 = random.randint(0,9)
ran2 = chr(random.randint(65,90))
add = random.choice([ran1,ran2])
code = ”.join([code,str(add)])
return code
rand_n = random_num()
print(“验证码:”,rand_n)
运行结果:
大家可以根据自己的需求,调用上述python模块~如需更多python实用知识,点击进入云海天Python教程网。