python怎么产⽣随机浮点数_python3⽣成随机数的⼏种常⽤⽅
法
前⾔: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 randomsamples = {"Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun" }for i in range(2): ret = random.sample(samples, 2) print("在样本samples中随机选择n
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个:
6、随机⽣成唯⼀流⽔号(时间戳)
import datetime; import random; for i in range (0,1): nowTime=w().strftime("%Y%m%d%H%M%S") randomNum=random.randin 7、随机⽣成验证码random python
import randomdef random_num(): code = '' for i in range(4): ran1 = random.randint(0,9) ran2 = chr(random.randint(65,90)) add = random
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论