如何用python随机生成数字(生成随机数的几种常用方法)

 分类:IT知识时间:2023-05-12 07:31:03点击:

python中生成随机数主要用到random模块,方法主要包括:randint、uniform、random、sample、choice等几种常用方法;

本篇教程就来说说这几种方法的使用方式,以及唯一流水号(时间戳)和验证码的实例展示

环境:Mac OS 10.14.6/Windows10、python3.7.3

1、在[a, b]之间产生随机整数(randint方法)

importrandom; fori in range(2): ret = random.randint(1000, 9999) print("在[a, b]之间产生随机整数:random.randint(1000, 9999)=",ret)

2、[a, b]之间产生随机浮点数(uniform方法)

importrandom; fori 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; fori inrange(2): ret = random.random() print("在[0.0, 1.0)之间产生随机浮点数:random.random() = ",ret)

4、在样本samples中随机选择n个(sample方法)

importrandom samples = {"Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"} fori in range(2): ret = random.sample(samples, 2) print("在样本samples中随机选择n个:random.sample(samples, 2) = ",ret)

5、在序列list1中随机选择1个(choice方法)

importrandom list1 = ("hello", "world", 'we', 'are', "learning", "python", 'very', 'good') fori in range(2): ret = random.choice(list1) print("在序列list1中随机选择1个:random.choice(list1) =",ret)

6、随机生成唯一流水号(时间戳)

import datetime; import random; fori in range (0,1): nowTime=datetime.datetime.now().strftime("%Y%m%d%H%M%S") randomNum=random.randint(0,99) ifrandomNum<=10: randomNum=str(0)+str(randomNum) uniqueNum=str(nowTime)+str(randomNum) print("时间戳:",uniqueNum)

7、随机生成验证码

importrandomdefrandom_num():code= ''fori in range(4):ran1= random.randint(0,9)ran2= chr(random.randint(65,90))add= random.choice([ran1,ran2])code= ''.join([code,str(add)])returncoderand_n= random_num()print("验证码:",rand_n)

除注明外的文章,均为来源:老汤博客,转载请保留本文地址!
原文地址: