python-- random 模块
random
random模块很简单,就是生成随机数
import random print(random.random()) # 随机生成[0,1)的小数 print(random.uniform(1, 3)) # 随机生成(1,3)的小数 print(random.randint(1, 4)) # 随机生成[1,4]的整数 print(random.randrange(1, 4)) # 随机生成[1,4)的整数 print(random.randrange(1, 9, 2)) # 随机生成[1,9)的整数,步长为2 print(random.choice('hello')) # 从字符串里随机取一个字符 print(random.choice(["hello", "boy", "gril"])) # 从列表里随机取一个值 print(random.sample('abcde', 2)) # 从序列中随机取两个
结果:
0.8978876800808587 2.791243761557495 2 1 7 l gril ['d', 'b']
例
import random a = [1, 2, 3, 4, 5, 6] random.shuffle(a) # 将列表打乱,在原列表的基础上打乱顺序 print(a)
结果:
[3, 5, 4, 6, 1, 2]
生成 5 位随机验证码
import random checkcode = '' for i in range(5): current = random.randrange(0, 5) if current == i: tmp = chr(random.randint(65, 90)) else: tmp = random.randint(0, 9) checkcode += str(tmp) print(checkcode)
结果:
M79GQ
例
import random for i in range(5): # 需要两个参数,第一个是数据源,第二个是在数据源里生成几个 # 返回的是列表 num = random.sample('123456asdfg', 5) print(num)
结果:
['1', '2', 'a', '5', 'd'] ['1', '3', 'a', '4', 's'] ['3', 'g', 'f', '4', '5'] ['1', '3', '5', '2', '6'] ['5', 'f', '4', '2', '3']
例
import random for i in range(5): # 需要两个参数,第一个是数据源,第二个是在数据源里生成几个 num = ''.join(random.sample('123456asdfg', 5)) print(num)
结果:
451d3 as1f6 g1afs 12356 fsd6g
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
2020-03-05 unittest--断言