.random() 0~1的随机数
1 import random 2 ret=random.random() 3 print(ret) 4 >>>0.03568971325272263
.randint( x,y) x~y 的随机数包过y
1 import random 2 ret=random.randint(1,3) 3 print(ret) 4 >>>3
.randrange( x,y) x~y的随机数 不包过y
1 import random 2 ret=random.randrange(1,3) 3 print(ret)
.choice() 里面加可迭代对象 例如:列表 两个就是百分之五十的概率
1 import random 2 ret=random.choice([11,22,33]) 3 print(ret) 4 >>>11
.sample() 随机选则两个
1 import random 2 ret=random.sample([11,22,33],2) 3 print(ret) 4 >>>[33, 22]
.uniform() 随机的范围
1 import random 2 ret=random.uniform(0,3) 3 print(ret) 4 >>>2.857569577421737
.shuffle() 打乱顺序
1 import random 2 v=[1,2,3,4,5,6,7] 3 random.shuffle(v) 4 print(v) 5 >>>[7, 5, 2, 4, 3, 6, 1]
验证码
1 import random 2 def v_code(): 3 ret="" 4 for i in range(6): 5 num=random.randint(0,9) 6 alf=chr(random.randint(65,122)) 7 v=str(random.choice([num,alf])) 8 ret+=v 9 return ret 10 print(v_code()) 11 >>>8z6bZ1