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]
