Python 使用random模块生成随机数

需要先导入 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']
bWoAJclK
tsqao
[6, 1, 5, 3, 7]

猜你喜欢

转载自www.cnblogs.com/xioawu-blog/p/11059923.html