random与随机操作有关的模块
常用方法:
random() --- 返回0-1之见得一个随机浮点数。
调用:random.random()
例如:
>>> random.random() 0.027383887147843344 >>> random.random() 0.5061348573341105 >>> random.random() 0.015448646863463922
randint() --- 返回一个随机整数。
调用:random.randint(a, b) (a<=b)返回随机数n, a <= n<= b
例如:
>>> random.randint(1, 10) 6 >>> random.randint(1, 10) 3 >>> random.randint(1, 10) 7 >>> random.randint(1, 10) 8 >>> random.randint(1, 10) 9 >>> random.randint(1, 10) 9
randrange() --- 返回一个随机整数。
调用:random.randrange([start], stop[, step]) 从制定范围内,按制定递增计数取随机值(该随机值最大为stop-1),
例如:random.randrange(1, 10, 2) 即从[1, 3, 5, 7, 9]中取得一个随机数
>>> random.randrange(1,10, 2) 3 >>> random.randrange(1,10, 2) 5 >>> random.randrange(1,10, 2) 7 >>> random.randrange(1,10, 2) 5 >>> random.randrange(1,10, 2) 3 >>> random.randrange(1,10, 2) 7
choice() --- 从一个序列中随机取得一个元素。
调用:random.choice(sequence) (sequence指有序序列)
例如:
>>> random.choice([1,2,3,4,5,6]) 2 >>> random.choice([1,2,3,4,5,6]) 3 >>> random.choice([1,2,3,4,5,6]) 4 >>> random.choice([1,2,3,4,5,6]) 4 >>> random.choice([1,2,3,4,5,6]) 6 >>> random.choice('hello word!') 'd' >>> random.choice('hello word!') 'w' >>> random.choice('hello word!') 'r' >>> random.choice('hello word!') 'o' >>> random.choice('hello word!') 'o' >>> random.choice('hello word!') 'l' >>> random.choice('hello word!') '!'
sample() --- 从一个序列中取的制定个数的随机值。
调用:random.sample(sequence, n)
例如:
>>> random.sample([1,2,3,4,5,6], 3) [4, 3, 2] >>> random.sample([1,2,3,4,5,6], 3) [3, 2, 6] >>> random.sample([1,2,3,4,5,6], 3) [3, 4, 5] >>> random.sample("hello world!", 3) ['l', 'o', 'r'] >>> random.sample("hello world!", 3) ['!', 'd', 'e'] >>> random.sample(("hello world!"), 3) ['l', 'e', 'l'] >>> random.sample(("hello world!"), 3) ['l', 'o', 'w'] >>> random.sample(("hello world!"), 3) ['l', 'd', 'o']