valorchang

需要先导入 random  模块,然后通过 random 静态对象调用该一些方法。

random() 函数中常见的方法如下:

 

复制代码
 1 # coding: utf-8
 2 # Team : Quality Management Center
 3 # Author:Carson
 4 # Date :2019/6/20 17:12
 5 # Tool :PyCharm
 6 
 7 import random
 8 import string
 9 
10 
11 print(random.random())                   # 产生 0 到 1 之间的随机浮点数
12 print(random.randint(1, 10))             # 产生 1 到 10 的一个整数型随机数
13 print(random.uniform(1, 5))             # 产生  1 到 5 之间的随机浮点数,区间可以不是整数
14 print(random.choice(\'tomorrow\'))       # 从序列中随机选取一个元素
15 print(random.choice([\'剪刀\', \'石头\', \'布\'])) # 随机选取字符串
16 print(random.randrange(1, 100, 2))       # 生成从1到100的间隔为2的随机整数
17 print(random.sample(\'zyxwedcba\', 5))      # 多个字符中生成指定数量的随机字符
18 # 从a-zA-Z0-9生成指定数量的随机字符:
19 ran_str = \'\'.join(random.sample(string.ascii_letters + string.digits, 8))
20 print(ran_str)
21 # 多个字符中选取指定数量的字符组成新字符串:
22 print \'\'.join(random.sample([\'z\',\'y\',\'x\',\'w\',\'v\',\'u\',\'t\',\'s\',\'r\',\'q\',\'p\',\'o\',\'n\',\'d\',\'c\',\'b\',\'a\'], 5))
23 # 将序列a中的元素顺序打乱
24 a = [1, 3, 5, 6, 7]
25 random.shuffle(a)
26 print(a)
复制代码

输出结果如下:

复制代码
0.836604144604
8
3.57866972595
r
石头
35
[\'d\', \'z\', \'e\', \'b\', \'y\']
gT8ByCrp
tsqao
[6, 1, 5, 3, 7]

分类:

技术点:

相关文章:

  • 2021-11-30
  • 2021-10-19
  • 2021-10-19
  • 2021-06-20
  • 2021-10-19
  • 2021-12-10
  • 2021-11-30
  • 2022-01-05
猜你喜欢
  • 2021-12-10
  • 2021-10-19
  • 2021-10-19
  • 2021-10-19
  • 2021-10-28
  • 2021-10-19
  • 2021-10-19
相关资源
相似解决方案