1、random(self):
Get the next random number in the range [0.0, 1.0)
取0到1直接的随机浮点数
import random print(random.random()) C:\python35\python3.exe D:/pyproject/day21模块/random随机模块.py 0.3105503800442595
2、randint(self, a, b)
Return random integer in range [a, b], including both end points.
返回a,b之间的随机整数,包括a和b
import random print(random.randint(5,99)) C:\python35\python3.exe D:/pyproject/day21模块/random随机模块.py 53
3、randrange(self, start, stop=None, step=1, _int=int):
Choose a random item from range(start, stop[, step]).
This fixes the problem with randint() which includes the
endpoint; in Python this is usually not what you want
返回a,b直接的随机整数,不包括b,就是>=a 小于b的范围
import random print(random.randrange(1,9)) C:\python35\python3.exe D:/pyproject/day21模块/random随机模块.py 3
还可以指定步长
import random print(random.randrange(1,9,step=2)) C:\python35\python3.exe D:/pyproject/day21模块/random随机模块.py 5
4、choice(self, seq)
Choose a random element from a non-empty sequence [?el?m?nt] 元素 sequence 序列
取一个不是空的序列里面的随机的一个元素
import random print(random.choice([11,22,33])) C:\python35\python3.exe D:/pyproject/day21模块/random随机模块.py 22
5、sample(self, population, k)
Chooses k unique random elements from a population sequence or set
选择k个随机元素从序列里面或者是集合里面,给返回的是一个列表
下面这个例子就是从集合里面随机取2个元素
import random print(random.sample({11,22,"gouguoqi",66},2)) C:\python35\python3.exe D:/pyproject/day21模块/random随机模块.py [‘gouguoqi‘, 11]
6、uniform(self, a, b):
Get a random number in the range [a, b) or [a, b] depending on rounding
选择a,b之间的随机数的浮点数
import random print(random.uniform(2,900)) C:\python35\python3.exe D:/pyproject/day21模块/random随机模块.py 621.520221600369
7、shuffle(self, x, random=None)
就是对列表中的元素进行重新洗牌(打乱顺序,没什么卵用)
import random ret=[11,22,33,44,55] random.shuffle(ret) print(ret) C:\python35\python3.exe D:/pyproject/day21模块/random随机模块.py [33, 22, 55, 44, 11]
8、制作五位数随机验证码
import random def v_code(): ret="" for n in range(5):#循环几次 num=random.randint(0,9)#取0-9之间的随机数字 alf=chr(random.randint(65,122))#65到122之间的chr就是小写a到z和大写A到Z的范围 s=str(random.choice([num,alf]))#用choice的方法随机从列表里面取一个元素,转换成str ret+=s#每次循环给ret加个s,s是字符串,所以最后ret就是5位数字和字母组合的验证码 return ret print(v_code()) C:\python35\python3.exe D:/pyproject/day21模块/random随机模块.py 6s070
原文地址:https://www.cnblogs.com/gouguoqilinux/p/9160468.html
时间: 2024-10-12 14:44:00