random
1.简介
random是用于生成随机数,我们可以利用它随机生成数字或者选择字符串
>>> import random
>>> dir(random)
['BPF', 'LOG4', 'NV_MAGICCONST', 'RECIP_BPF', 'Random', 'SG_MAGICCONST', 'SystemRandom', 'TWOPI', 'WichmannHill', '_BuiltinMethodType', '_MethodType', '__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '_acos', '_ceil', '_cos', '_e', '_exp', '_hashlib', '_hexlify', '_inst', '_log', '_pi', '_random', '_sin', '_sqrt', '_test', '_test_generator', '_urandom', '_warn', 'betavariate', 'choice', 'division', 'expovariate', 'gammavariate', 'gauss', 'getrandbits', 'getstate', 'jumpahead', 'lognormvariate', 'normalvariate', 'paretovariate', 'randint', 'random', 'randrange', 'sample', 'seed', 'setstate', 'shuffle', 'triangular', 'uniform', 'vonmisesvariate', 'weibullvariate']
2.常用函数
random.random()用于生成一个随机浮点数:
random() -> x in the interval [0, 1).
>>> import random
>>> random.random()
0.999410896951364
random.uniform(a,b)用于生成一个指定范围内的随机浮点数,a,b为上下限
Get a random number in the range [a, b) or [a, b] depending on rounding.
只要a!=b,就会生成介于两者之间的一个浮点数,若a=b,则生成的浮点数就是a
>>> random.uniform(0,6.7)
6.641371899714727
>>> random.uniform(10,20)
17.29561748518131
>>> random.uniform(20,10)
19.798448766411184
>>> random.uniform(10,10)
10.0
random.randint(a,b)
用于生成一个指定范围内的整数,a为下限,b为上限,生成的随机整数a<=n<=b;若a=b,则n=a;若a>b,报错
Return random integer in range [a, b], including both end points.
>>> random.randint(10,10)
10
>>> random.randint(10,20)
12
>>> random.randint(20,10)
Traceback (most recent call last):
File "<pyshell#13>", line 1, in <module>
random.randint(20,10)
File "C:\Python27\lib\random.py", line 242, in randint
return self.randrange(a, b+1)
File "C:\Python27\lib\random.py", line 218, in randrange
raise ValueError, "empty range for randrange() (%d,%d, %d)" % (istart, istop, width)
ValueError: empty range for randrange() (20,11, -9)
random.randrange([start], stop, [,step])
从指定范围内,按指定基数递增的集合中获取一个随机数,基数缺省值为1
Choose a random item from range(start, stop[, step]).
This fixes the problem with randint() which includes the
endpoint; in Python this is usually not what you want.
>>> random.randrange(10,100,5)
80
random.choice(sequence)
从序列中获取一个随机元素,参数sequence表示一个有序类型,并不是一种特定类型,泛指list,tuple,字符串等
Choose a random element from a non-empty sequence.
>>> random.choice([1,3,8,9])
8
>>> random.choice([1,3,8,9])
9
>>> random.choice([1,3,8,9])
9
>>>
random.shuffle(x[, random])
用于将一个列表中的元素打乱
>>> a = [1,2,3,4,5]
>>> random.shuffle(a)
>>> a
[4, 5, 2, 1, 3]
>>> random.shuffle(a)
>>> a
[3, 2, 5, 1, 4]
random.sample(sequence, k)
从指定序列中随机获取k个元素作为一个片段返回,sample函数不会修改原有序列
>>> a = [1,2,3,4,5]
>>> random.sample(a,3)
[1, 4, 5]
>>> random.sample(a,3)
[1, 2, 5]
>>> a
[1, 2, 3, 4, 5]