[Python3] 032 常用模块 random
2024-09-05 17:07:38
目录
random
- 必要的导入
>>> import random
- 必要的说明
- random 是伪随机
1. random.random()
- 返回值:x in the interval [0, 1)
>>> random.random()
0.32777843950175867
>>> random.random()
0.6195138047287055
2. random.choice()
- 格式:
random.choice(非空序列)
- 返回值:序列中的某个值
>>> lst = [i for i in range(10)]
>>> lst
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> random.choice(lst)
4
>>> random.choice(lst)
2
3. random.shuffle()
- 功能:随机打乱列表
- 格式:
random.shuffle(列表)
- 返回值:打乱顺序之后的列表
>>> lst
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> random.shuffle(lst)
>>> lst
[7, 6, 0, 5, 9, 4, 1, 2, 3, 8]
>>> random.shuffle(lst)
>>> lst
[9, 6, 4, 3, 2, 0, 8, 1, 7, 5]
4. random.randint()
- 格式:
random.randint(a, b)
- 返回值:random integer in range [a, b]
>>> random.randint(1, 100)
26
>>> random.randint(1, 100)
100
5. random.randrange()
- 格式:
random.randrange(a, b)
- 返回值:random integer in range [a, b)
- 其实,randint 就是调用了 randrange
- 源码
def randint(self, a, b):
"""Return random integer in range [a, b], including both end points.
"""
return self.randrange(a, b + 1)
- 举例
>>> random.randrange(1, 100)
17
>>> random.randrange(1, 100)
37
6. 造个轮子
- 其实这个轮子在 Js 中造过
- Js 中的 Math.random() 返回一个 (0, 1] 的小数
- 想要一个 [a, b] 的整数,需要手动封装
- 这回用 Python3 造一个
def random_test(start:int, stop:int) ->int:
""" 此函数不考虑输入错误的情况 """
return int(random.random() * (stop - start + 1)) + start
print(random_test(1, 6))
最新文章
- C#.NET 大型通用信息化系统集成快速开发平台 4.1 版本 - 角色成员功能的改进支持公司加入到角色
- 【代码笔记】iOS-后台运行,可以选择在前台或后台或前后台
- HTML5游戏开发引擎,初识CreateJS
- 《zw版·Halcon-delphi系列原创教程》cgal与opencv,Halcon
- Linux grep和find的区别
- Unity3D 4.x 使用Mecanim实现动画控制
- java--多线程之前台幕后
- 小白都会超详细--ELK日志管理平台搭建教程
- HTML5-全局属性
- 025_lua脚本语言
- git多账号切换
- Django_models下划线__正反查询,对象正反查询
- Apollo的Oracle适配
- Java第三阶段学习(十二、HttpServletRequest与HttpServletResponse)
- Centos 安装 Wireshark
- JAVA AQS源码分析
- Java中获取运行代码的类名、方法名
- [NOIP2011]刷水
- 开源框架AsyncHttpClient使用
- 用外部物理路由器时使用Neutron dhcp-agent提供的metadata服务(by quqi99)