Python標准庫中的random函數,可以生成隨機浮點數、整數、字符串,甚至幫助你隨機選擇列表序
列中的一個元素,打亂一組數據等。
random中的一些重要函數的用法:
1 )、random() 返回0<=n<1之間的隨機實數n;
2 )、choice(seq) 從序列seq中返回隨機的元素;
3 )、getrandbits(n) 以長整型形式返回n個隨機位;
4 )、shuffle(seq[, random]) 原地指定seq序列;
5 )、sample(seq, n) 從序列seq中選擇n個隨機且獨立的元素;
詳細介紹:
random.random()函數是這個模塊中最常用的方法了,它會生成一個隨機的浮點數,范圍是在0.0~1.0之間。
random.uniform()正好彌補了上面函數的不足,它可以設定浮點數的范圍,一個是上限,一個是下限。
random.randint()隨機生一個整數int類型,可以指定這個整數的范圍,同樣有上限和下限值,python random.randint。
random.choice()可以從任何序列,比如list列表中,選取一個隨機的元素返回,可以用於字符串、列表、元組等。
random.shuffle()如果你想將一個序列中的元素,隨機打亂的話可以用這個函數方法。
random.sample()可以從指定的序列中,隨機的截取指定長度的片斷,不作原地修改。
使用例子:
# -*- coding: utf-8 -*- import random print "\n\t" print "start test choice:" foo = ['a', 'b', 'c', 'd', 'e'] print random.choice(foo) print "\n\t" # -*- coding: utf-8 -*- import random print "\n\t" print "start test choice:" foo = ['a', 'b', 'c', 'd', 'e'] print random.choice(foo) print "\n\t" print "start test slice:" list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] slice = random.sample(list, 5) #從list中隨機獲取5個元素,作為一個片斷返回 print slice print list #原有序列並沒有改變 print "\n\t" print "start test uniform:" print random.uniform(10, 20) print random.uniform(20, 10) print "\n\t" print "start test randint:" print random.randint(10, 20) print random.randint(0, 1) print "\n\t" print "start test random:" print random.random()*1000 print random.random() print "\n\t" print "start test shuffle:" li=range(20) print random.shuffle(li) print li
start test choice: a start test slice: [1, 4, 10, 8, 5] [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] start test uniform: 10.4775179432 10.5882871067 start test randint: 20 0 start test random: 483.103200723 0.430725744563 start test shuffle: None [13, 6, 5, 2, 10, 18, 0, 7, 3, 16, 4, 11, 15, 12, 9, 8, 17, 19, 1, 14]