random模块

Python的random比JavaScript里的random功能要多一些(虽然两者有着本质上的不同,一个是模块,一个是Math对象里的方法)。

random.random() 生成一个0-1之间的随机数

>>> random.random()
0.7876356442055253
>>> random.random()
0.45350051121098045
>>> random.random()
0.6433521369639733

random.choice() 从序列中生成一个随机数

>>> random.choice(['yes', 'no', 'hehe'])
'yes'
>>> random.choice(['yes', 'no', 'hehe'])
'hehe'
>>> random.choice(['yes', 'no', 'hehe'])
'no'
>>> random.choice(['yes', 'no', 'hehe'])
'hehe'

random.randint() 随机返回一个指定范围内的整数

>>> random.randint(2, 5)
2
>>> random.randint(2, 5)
3
>>> random.randint(2, 5)
3
>>> random.randint(2, 5)
5
>>> random.randint(2, 5)
3
>>> random.randint(2, 5)
4

 random.randrange 从指定范围内,按指定基数递增的集合中,获取一个随机数

>>> random.randrange(0, 9, 3)                                                                                           
6
>>> random.randrange(0, 9, 3)
3
>>> random.randrange(0, 9, 3)
6
>>> random.randrange(0, 9, 3)
6
>>> random.randrange(0, 9, 3)
6
>>> random.randrange(0, 9, 3)
3
>>> random.randrange(0, 9, 3)
0

random.sample 从指定序列中生成指定长度的随机片段

>>> random.sample('0123456789', 4)
['3', '9', '1', '0']
>>> random.sample('0123456789', 4)
['5', '4', '2', '1']
>>> random.sample('0123456789', 4)
['1', '5', '2', '6']
>>> random.sample('0123456789', 4)
['7', '0', '5', '1']
>>> random.sample('0123456789', 4)
['1', '4', '2', '9']
>>> random.sample('0123456789', 4)
['8', '5', '6', '4']

random.uniform 随机生成指定范围内的浮点数

>>> random.uniform(1, 8)
4.17446701119013
>>> random.uniform(1, 8)
1.9009697673812929

random.shuffle 洗牌

>>> list = [1,2,3,4,5,6]
>>> random.shuffle(list)
>>> list
[3, 4, 1, 6, 5, 2]
>>> random.shuffle(list)
>>> list
[2, 5, 3, 1, 6, 4]
>>> random.shuffle(list)
>>> list
[5, 3, 6, 1, 2, 4]
原文地址:https://www.cnblogs.com/allenzhang-920/p/9023106.html