前言: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)
![2e07df442fefe71524abb688636f5d01.png](https://i-blog.csdnimg.cn/blog_migrate/73adf9ab08ad52e1746afbbcbab77c92.jpeg)
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)
![10624f1d766eb1a6a8d96d702c91ac44.png](https://i-blog.csdnimg.cn/blog_migrate/70a638b2333024fb1bcff37395da8cc0.jpeg)
3、在[0.0, 1.0)之间产生随机浮点数(random方法)
import random; for i in range(2): ret = random.random() print("在[0.0, 1.0)之间产生随机浮点数:random.random() = ",ret)
![0bd61ab715f95264477fc02065c92302.png](https://i-blog.csdnimg.cn/blog_migrate/8280c8e792e67ecb095e4bac78982e71.jpeg)
4、在样本samples中随机选择n个(sample方法)
import randomsamples = {"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)
![05630361d9a6628eb98781a3243a14ac.png](https://i-blog.csdnimg.cn/blog_migrate/f32da9bf42dfac4456b889bcbcd1e58e.jpeg)
5、在序列list1中随机选择1个(choice方法)
import randomlist1 = ("hello", "world", 'we', 'are', "learning", "python", 'very', 'good')for i in range(2): ret = random.choice(list1) print("在序列list1中随机选择1个:random.choice(list1) =",ret)
![acedbbc9d42bc1df78781ae7f8627bf6.png](https://i-blog.csdnimg.cn/blog_migrate/f77392517b7e1e25776eedaa411998ef.jpeg)
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 randomdef 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 coderand_n = random_num()print("验证码:",rand_n)
![91ff1b84d5e0a80229eea72066d3e592.png](https://i-blog.csdnimg.cn/blog_migrate/79c8af4eaf46dab03d1aa6909385e8c3.jpeg)