随机数是由程序随即产生的数字,常见的图片验证码,12306的图片验证等,这节我们来认识Python中的随机数模块。
- random模块
Python中产生随机数需要导入random模块:
import random
随机数模块常用方法:
- random.randint(a, b):返回a和b之间的随机整数;
>>> import random
>>> random.randint(0, 10)
8
>>> random.randint(0, 10)
7
>>> random.randint(0, 10)
10
>>>
- random.random():返回0到1之间随机数(不包括1);
>>> random.random()
0.8836361984681352
>>> random.random()
0.013648077769505496
>>> random.random()
0.7267135453127417
>>>
- random.choice(seq):在不为空的序列中随机选择一个元素;
>>> s = 'helloWorld'
>>> random.choice(s)
'o'
>>> random.choice(s)
'r'
- random.sample(population, k):在一个序列或者集合中选择k个随机元素(),返回由K个元素组成新的列表;(k的值小于population的长度)
>>> random.sample('12345', 2)
['1', '2']
>>> random.sample('12345', 5)
['2', '1', '3', '4', '5']
>>> random.sample('12345', 6) #k值超出population范围导致程序异常
Traceback (most recent call last):
File "<pyshell#41>", line 1, in <module>
random.sample('12345', 6)
File "D:\python36\lib\random.py", line 317, in sample
raise ValueError("Sample larger than population or is negative")
ValueError: Sample larger than population or is negative
>>>
- random.uniform(a, b):产生一个指定范围内的随机浮点数
若a < b,随机数n范围:a <= n <= b;
若a > b,随机数n范围:b <= n <= b;
>>> s = 'helloWorld'
>>> random.uniform(1,10)
1.9304756617571137
>>> random.uniform(10, 1)
2.872422460231057
>>>
- random.randrange(start, stop=None, step=1, _int=<class 'int'>) :在rang(start, stop,step)中选择一个随机数;
>>> random.randrange(1, 10, 1) #[1,10)之间随机整数
5
>>> random.randrange(1, 10, 1)
2
>>> random.randrange(1, 100, 2) #[1, 100)之间随机奇数
33
>>> random.randrange(1, 100, 2)
5
- random.shuffle(x, random=None):将列表顺序打乱;
>>> l = ['C', 'C++', 'Java', 'C#', 'Python']
>>> random.shuffle(l)
>>> l
['C++', 'C', 'Java', 'C#', 'Python']
>>> random.shuffle(l)
>>> l
['C', 'Python', 'C++', 'C#', 'Java']
>>>