random模塊用於生成隨機數。 random.randint(a, b):html
生成隨機整數n (a <= n <= b)python
random.randint(1,10) 10dom
random.random():ui
生成隨機浮點數n (0 <= n < 1.0).net
print random.random() 0.5240641875 print random.random() 0.234854238114rest
random.uniform(a, b):code
生成隨機浮點數n (若是a>b,則b <= n <= a。若是b>a,則a <= n <= b)orm
print random.uniform(1, 10) 3.35351445677 print random.uniform(1, 10) 2.46947884885 print random.uniform(100, 10) 45.9025693327htm
random.randrange([start], stop[, step]):blog
在start到stop的範圍內,根據由step指定步長造成的集合裏隨機獲取一個元素。
換而言之,它是從range(start, stop, step)裏隨機獲取一個元素,等價於random.choice(range(start, stop, step))。
(官方文檔說:This is equivalent to choice(range(start, stop, step)), but doesn’t actually build a range object.)
random.randrange(1, 10, 2) 9 random.randrange(1, 10) 8 random.randrange(10) 7
注意:按語法說明寫「random.randrange(, 10, 2)」或者「random.randrange(, 10)」會提示語法錯誤。 random.choice(seq):
從序列seq中隨機獲取一個元素。
seq範指list, tuple, 字符串等等。seq爲空時返回一個IndexError錯誤。
print random.choice("Python") t print random.choice(["a", "ab", "abc"]) ab print random.choice(("a", "ab", "abc")) ab
random.shuffle(x[, random])
打亂列表x裏元素的順序(不適用於元組和字符串)
p = (["a", "ab", "abc"]) random.shuffle(p) p
p = (("a", "ab", "abc")) random.shuffle(p) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.6/random.py", line 275, in shuffle x[i], x[j] = x[j], x[i] TypeError: 'tuple' object does not support item assignment
p = ("Python") random.shuffle(p) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.6/random.py", line 275, in shuffle x[i], x[j] = x[j], x[i] TypeError: 'str' object does not support item assignment
random.seed([x])
初始化隨機數生成器,若是不提供x或者爲None,就以系統時間作爲種子。
這篇文檔的代碼在沒有使用seed()時老是生成相同的數字,沒有任何隨機。http://blog.csdn.net/huithe/article/details/5254137,代碼以下:
import os,random,sys,time
while True:
father = os.fork() if father: time.sleep(2) rd = 7 else: # random.seed() rd = random.choice([2,3,4,5]) print rd time.sleep(2) sys.exit(0)
的確沒有生成隨機數,可是程序在cygwin下運行會出錯:
$ python test7.py 5 5 5 1 [main] python 10704 D:\cygwin\bin\python.exe: *** fatal error - unable to remap \?\D:\cygwin\lib\python2.6\lib-dynload_codecs_cn.dll to same address as parent: 0x360000 != 0x3D0000 Stack trace: Frame Function Args 0028B3C8 6102796B (0028B3C8, 00000000, 00000000, 00000000) 0028B6B8 6102796B (6117EC60, 00008000, 00000000, 61180977) 0028C6E8 61004F1B (611A7FAC, 61243684, 00360000, 003D0000) End of stack trace 0 [main] python 14488 fork: child 10704 - died waiting for dll loading, errno 11 Traceback (most recent call last): File "test7.py", line 5, in <module> father = os.fork() OSError: [Errno 11] Resource temporarily unavailable
把random.seed()前面的#去掉,生成的數字是隨機的。
{
據唐唐說cygwin的fork()有問題,這篇文檔也證明了這個說法:http://www.lc365.net/blog/b/8585/
cygwin官方文檔(http://cygwin.com/cygwin-ug-net/highlights.html)裏看到這一句:
The fork call in Cygwin is particularly interesting because it does not map well on top of the Win32 API. This makes it very difficult to implement correctly. Currently, the Cygwin fork is a non-copy-on-write implementation similar to what was present in early flavors of UNIX.
} random.sample(population, k)
在population序列(字符串、列表、元組均可以)中隨機獲取由k指定數量的元素。
random.sample((["a", "ab", "abc", "abcd", "abcde", "abcdef"]), 3) ['a', 'ab', 'abcde'] random.sample((("a", "ab", "abc", "abcd", "abcde", "abcdef")), 3) ['abc', 'abcdef', 'ab'] random.sample(("python"), 3) ['o', 'h', 'p']
若是要從一個範圍的數字裏隨機獲取指定數量的數,最快最節省內存的方法:
random.sample(xrange(1, 1000000 ,2), 3) [717481, 410151, 700227]
random模塊還有其餘一些方法就不一一列舉了。