Python 中的的random模块(随机数模块)

Python 中的的random模块(随机数模块)

(1) 取随机小数
  1. random.random() ,随机取一个( 0-1)之间的随机小数
  2. random.uniform(a,b) ,随机取一个(a-b)之间的随机小数
import random
print(random.random())
print(random.uniform(1,2))
#输出结果:
#0.5197468585617347
#1.8517038679031552
(2) 取随机整数
  1. random.randint(1,3) ,随机取一个[1-3]的整数,包含1和3
    1. random.randrange(5) ,随机取一个[0-5)的整数,不包含5
  2. random.randrange(1,5) ,随机取一个[1-5)的整数,不包含5
  3. random.randrange(1,5,2) ,随机取一个[1-5)中除了步长为2的整数,不包含5
import random
print(random.randint(1,10))
print(random.randrange(4))
print(random.randrange(1,10))
print(random.randrange(1,10,2))
#输出结果
#8
#2
#1
#5
(3) 抽取列表中的随机元素
  1. random.choice(list) ,随机从list中取一个元素
  2. random.sample(list,N) ,随机从list中取N个元素(N个元素不重复)
import random
lst=['1','2','3','a','b','c']
print(random.choice(lst))
print(random.sample(lst,1))
print(random.sample(lst,3))
print(random.sample(lst,6))
#输出结果
#c
#['a']
#['b', 'c', '3']
#['c', '1', 'b', '2', 'a', '3']
(4) 打乱一个列表的顺序
  1. random.shuffle(list) 随机打乱原来列表,不会返回新列表(如洗牌)
import random
lst=['1','2','3','a','b','c']
print(random.shuffle(lst))#输出None,表示没有返回值
print(lst)
#输出结果
#None
#['1', 'b', '3', '2', 'c', 'a']
(5)random模块常用的操作
  1. 生成验证码
import random
def Captcha(N=4,letter=True):#默认4位验证码,且包含字母
    ret=''
    for i in range(N):#获取足够的验证位数
        res=str(random.randint(0,9))#获取数字
        if letter:#判断验证码是否需要字母
            res1=chr(random.randint(97,122))#获取小写字母
            res2=chr(random.randint(65,90))#获取大写字母
            res=random.choice([res,res1,res2])#随机抽取每一位验证码具体元素
        ret=ret+res
    return ret#返回生成验证码
print(Captcha())#获取四位带字母验证码
print(Captcha(6))#获取六位带字母验证码
print(Captcha(6,letter=False))#获取六位纯数字验证码
#输出结果
#0HP1
#cFaYSo
#614171
  1. 拼手气红包
#先把金额分配完毕,然后再分给具体个人
#并且让每个人获得红包的概率相同
import random
def RedEnvelope(Amount,Quantity):#传入两个参数Amount(金额),Quantity红包数量
    res=[]#红包池
    for i in range(Quantity-1):
        ele=format(random.uniform(0.01,Amount),'.2f')#格式话红包金额,0.01最小
        res.append(ele)#将红包放入红包池
        Amount=Amount-float(ele)#最后的红包放入红包池
    res.append(format(Amount,'.2f'))
    while len(res)!=0:
        yield res.pop()#抢一个红包池少一个      
RedEnvelope=RedEnvelope(100,5)
for i in range(5):
    print(RedEnvelope.__next__())

抢红包程序运行结果图:
效果图

发布了66 篇原创文章 · 获赞 7 · 访问量 2380

猜你喜欢

转载自blog.csdn.net/qq_45894553/article/details/104859698