python模块---random

时间:2019-10-28
本文章向大家介绍python模块---random,主要包括python模块---random使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

random

 

random

  • 取随机数
 
  • 取一个随机浮点数。
In [2]:
import random
random.random()
Out[2]:
0.9896051007555908
 
  • 在1-3取一个随机数数(整型)。
In [6]:
a=random.randint(1,3)
b=random.randint(1,3)
c=random.randint(1,3)
print(a,b,c)
 
3 1 2
 
  • 在序列中随机取一个元素。
In [7]:
e=random.choice('hello')
f=random.choice('hello')
g=random.choice('hello')
print(e,f,g)
 
e l l
 
  • 在序列中随机取一个元素,指定元素的个数。
In [8]:
seq1=random.sample('hello',2)
seq2=random.sample('hello',2)
seq3=random.sample('hello',2)
print(seq1,seq2,seq3)
 
['l', 'h'] ['l', 'l'] ['e', 'h']
 
  • 打乱一个有序列表
In [9]:
ls1=[1,2,3,4,5,6]
random.shuffle(ls1)
print(ls1)
 
[5, 2, 6, 3, 4, 1]
 

使用random块取随机验证码

In [10]:
checkcode=''
for i in range(4):
    current=random.randint(0,9)
    checkcode+=str(current)
print(checkcode)
 
0346
 

字母加数字混合版

In [46]:
import random
checkcode1='' # 验证码寄存
for i in range(0,3): #三次 产生三组验证码,检验是否能生成
    for i in range (4):#执行次,产生4个随机字符
        current=random.randrange(0,4)#随机深沉一个数字和
        if current == i: # 用随机数和循环次数猜
            tmp=chr(random.randint(65,90))# 猜中了几生成一个字符
        else:
            tmp=random.randint(0,9)# 没有猜中就生成一个数字
        checkcode1+=str(tmp) #将生成的字母或者数字添加到变量里面
    print('验证码:',checkcode1)# 将生成的验证码打印出来
    checkcode1='' # 初始化验证码寄存器
        
 
验证码: 7S49
验证码: 6402
验证码: C02R

原文地址:https://www.cnblogs.com/yjc-z/p/11751121.html