random模块
随机 : 在某个范围内取到每一个值的概率是相同的
随机小数
random.random()) # 0-1之内的随机小数 random.uniform(1,5)) # 任意范围之内的随机小数
随机整数
random.randint(1,2))# [1,2] 包含2在内的范围内随机取整数 random.randrange(1,2) # [1,2)不包含2在内的范围内随机取整数 random.randrange(1,10,2) # [1,10)不包含10在内的范围内随机取奇数
随机抽取一个值或多个值
随机抽取 随机抽取一个值 lst = [1,2,3,'aaa',('wahaha','qqxing')] ret = random.choice(l) print(ret) 随机抽取多个值 #两个值或多个值不重复 ret = random.sample(lst,2) print(ret)
打乱顺序
打乱顺序 在原列表的基础上做乱序 lst = [1,2,3,'aaa',('wahaha','qqxing')] random.shuffle(lst) print(lst) 抽奖 \ 彩票 \发红包 \验证码 \洗牌
生成四位数随机验证码生成随机验证码0-9
基础版本 code = '' for i in range(4): num = random.randint(0,9) code += str(num) print(code) 函数版本 def rand_code(n=4): code = '' for i in range(n): num = random.randint(0,9) code += str(num) return code print(rand_code()) print(rand_code(6))
6位数字加字母验证码
6位 数字+字母 基础版 code = '' for i in range(6): rand_num = str(random.randint(0,9)) rand_alph = chr(random.randint(97,122)) rand_alph_upper = chr(random.randint(65,90)) atom_code = random.choice([rand_num,rand_alph,rand_alph_upper]) code += atom_code print(code) 函数版 def rand_code(n=6): code = '' for i in range(n): rand_num = str(random.randint(0,9)) rand_alph = chr(random.randint(97,122)) rand_alph_upper = chr(random.randint(65,90)) atom_code = random.choice([rand_num,rand_alph,rand_alph_upper]) code += atom_code return code ret = rand_code() print(ret) 数字/数字+字母 def rand_code(n=6 , alph_flag = True): code = '' for i in range(n): rand_num = str(random.randint(0,9)) if alph_flag: rand_alph = chr(random.randint(97,122)) rand_alph_upper = chr(random.randint(65,90)) rand_num = random.choice([rand_num,rand_alph,rand_alph_upper]) code += rand_num return code ret = rand_code(n = 4) print(ret)
实现抢红包
import random def red(money,num): r = random.sample(range(0,money*100),num-1) r.extend([0,money*100]) r.sort() return [(r[i+1]-r[i])/100 for i in range(num)] print(red(200,10)) print(sum(red(200,10))) #任意两个数之间的差值,等于这两个数之间任何两个数之间差值的总和,前提是这个序列是有序的 另外一种常规方法 import random lst=[] def redpacket(cash,person): if cash>0 and person !=1: n = round(random.uniform(0.01,cash-(0.01*person)),2) lst.append(n) person -= 1 cash -= n redpacket(cash,person) return lst else: lst.append(round(cash,2)) return lst print(redpacket(200,10)) print(sum(lst))