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))

最新文章

  1. C#.NET 大型通用信息化系统集成快速开发平台 4.1 版本 - 角色成员功能的改进支持公司加入到角色
  2. 【代码笔记】iOS-后台运行,可以选择在前台或后台或前后台
  3. HTML5游戏开发引擎,初识CreateJS
  4. 《zw版·Halcon-delphi系列原创教程》cgal与opencv,Halcon
  5. Linux grep和find的区别
  6. Unity3D 4.x 使用Mecanim实现动画控制
  7. java--多线程之前台幕后
  8. 小白都会超详细--ELK日志管理平台搭建教程
  9. HTML5-全局属性
  10. 025_lua脚本语言
  11. git多账号切换
  12. Django_models下划线__正反查询,对象正反查询
  13. Apollo的Oracle适配
  14. Java第三阶段学习(十二、HttpServletRequest与HttpServletResponse)
  15. Centos 安装 Wireshark
  16. JAVA AQS源码分析
  17. Java中获取运行代码的类名、方法名
  18. [NOIP2011]刷水
  19. 开源框架AsyncHttpClient使用
  20. 用外部物理路由器时使用Neutron dhcp-agent提供的metadata服务(by quqi99)

热门文章

  1. python 3 与python 2连接mongoDB的区别
  2. JavaScript的数组API函数
  3. XML的树结构与语法规则
  4. File类、FileInfo类、Directory类、DirectoryInfo类
  5. sh_05_列表遍历
  6. scala实战学习-尾递归函数
  7. LocalDate/LocalDateTime与String的互相转换示例(附DateTimeFormatter详解)
  8. windows 简单实用Elasticsearch
  9. js将伪数组转换为标准数组的多种方法
  10. c++匿名函数精简写法