Python随机数
来源:互联网 发布:淘宝卖切糕 编辑:程序博客网 时间:2024/04/29 10:35
“Anyone who considers arithmetical methods of producing random digits is, of course, in a state of sin.”
John von Neumann, 1951
Python中自带了随机数的模块random,它们编程当前往往是十分重要的。下面对random模块进行介绍。
random模块
- randint()
- random()
- uniform()
- randrange()
- choice()
- sample()
randint()
randint(a, b)用于生成随机的整数[a, b]。需要2个参数,分别指定随机数的上限和下限。
NB:此处包含上限和下限的值。
>>> random.randint(1, 10)6>>> random.randint(1, 10)3>>> random.randint(1, 10)4>>> random.randint(1, 10)10>>>
random()
random()用于生成随机的(0.0, 1.0)浮点数。
>>> random.random()0.8135945944158621>>> random.random()0.10820684120770308>>> random.random()0.8036909615265496>>>
uniform()
uniform(a, b)用于生成随机的[a, b]或者[b, a]浮点数。需要2个参数,分别指定随机数的上限和下限。而无论两者的大小。
>>> random.uniform(1, 10)9.877878726666212>>> random.uniform(1, 10)7.320900049560443>>> random.uniform(10, 1)9.26225787417653>>>
randrange()
randrange(stop),randrange(start, stop[, step])用于返回相当于使用range(stop)或者range(start, stop[, step])生成列表的随机一项的值。
>>> random.randrange(10)1>>> random.randrange(10)9>>> random.randrange(1, 10, 2)3>>> random.randrange(1, 10, 2)3>>> random.randrange(1, 10, 2)9>>>
choice()
choice(seq)随机返回序列seq中的一项。
>>> random.choice("!@#$%^&*()_+")'_'>>> random.choice("!@#$%^&*()_+")'+'>>> random.choice([1, 2, 3, 4])3>>> random.choice([1, 2, 3, 4])1>>>
sample()
sample(population, k)返回一个包含k个元素的列表,列表元素取自序列或者集合population,且列表元素唯一。
>>> random.sample([1, 2, 3, 4], 2)[4, 2]>>> random.sample([1, 2, 3, 4], 2)[1, 2]>>> random.sample("!@#$%^&*()_+", 3)['^', '&', '_']>>> random.sample("!@#$%^&*()_+", 3)[')', '#', '^']>>>
更多请参考Python标准库。
0 0
- python 随机数
- python 随机数
- python 随机数
- python 随机数
- python 随机数
- python 随机数
- python-- 随机数
- python 随机数
- python 随机数
- python 随机数
- python 随机数
- python : 随机数
- python随机数
- Python随机数
- python随机数
- python 随机数
- Python 随机数
- Python随机数
- 数据结构实践——后缀表达式
- 第4周项目3 单链表应用(1)
- 需要进行截图的控件的工具类
- 解读ASP.NET 5 & MVC6系列(11):Routing路由
- 第六周 项目2-建立链栈算法库
- Python随机数
- 一个winform带你玩转rabbitMQ
- SQLiite3: 数据库文件使用UTF-16编码
- android客户端学习-button按钮边框及圆角
- Android内存泄露案例分析
- 第7周—项目1 建立顺序环形队列算法库
- 【笔试面试】75道逻辑推理题及答案
- FullCalendar应用——新建日程事件
- 解读ASP.NET 5 & MVC6系列(12):基于Lamda表达式的强类型Routing实现