- 工信部備案號 滇ICP備05000110號-1
- 滇公安備案 滇53010302000111
- 增值電信業(yè)務(wù)經(jīng)營許可證 B1.B2-20181647、滇B1.B2-20190004
- 云南互聯(lián)網(wǎng)協(xié)會理事單位
- 安全聯(lián)盟認(rèn)證網(wǎng)站身份V標(biāo)記
- 域名注冊服務(wù)機構(gòu)許可:滇D3-20230001
- 代理域名注冊服務(wù)機構(gòu):新網(wǎng)數(shù)碼
1. random()函數(shù)
描述:random() 方法返回隨機生成的一個實數(shù),它在[0,1)范圍內(nèi)。
語法:
1 2 | import random random.random(); |
注意:random()是不能直接訪問的,需要導(dǎo)入 random 模塊,然后通過 random 靜態(tài)對象調(diào)用該方法。
實例演示:
1 2 3 4 5 | >>> import random >>> print random.random(); 0.803119901575 >>> print random.random(); 0.451592468747 |
2. randrange()函數(shù)
描述: randrange() 方法返回指定遞增基數(shù)集合中的一個隨機數(shù),基數(shù)缺省值為1。返回一個整數(shù)
語法
1 2 | import random random.randrange ([start,] stop [,step]) |
參數(shù):
start -- 指定范圍內(nèi)的開始值,包含在范圍內(nèi)
stop -- 指定范圍內(nèi)的結(jié)束值,不包含在范圍內(nèi)。
step -- 指定遞增基數(shù)
實例演示
1 2 3 4 5 6 7 8 | >>> print random.randrange( 10 ); 4 >>> print random.randrange( 5 , 10 ); 7 >>> print random.randrange( 5 , 10 , 3 ); 5 >>> print random.randrange( 5 , 10 , 3 ); 8 |
3.randint()函數(shù)
描述:randint()方法將隨機生成一個整數(shù),它在[x,y]范圍內(nèi) ;有點等價于randrange(x,y+1).
語法
1 2 | import random random.randint(x,y) |
參數(shù):
x -- 指定范圍內(nèi)的開始值,包含在范圍內(nèi)
y -- 指定范圍內(nèi)的結(jié)束值,包含在范圍內(nèi)。
實例演示
1 2 3 4 | >>> print random.randrange( 5 , 10 ); 9 >>> print random.randint( 5 , 10 ); 6 |
4. uniform()函數(shù)
描述:uniform() 方法將隨機生成下一個實數(shù),它在[x,y]范圍內(nèi)。返回一個浮點數(shù)
語法:
1 2 | import random random.uniform (x,y) |
參數(shù):
x -- 指定范圍內(nèi)的開始值,包含在范圍內(nèi)
y -- 指定范圍內(nèi)的結(jié)束值,包含在范圍內(nèi)。
實例演示
1 2 3 4 | >>> print random.uniform( 5 , 10 ); 9.13282585434 >>> print random.uniform( 9 , 10 ); 9.95958315062 |
5. choice()函數(shù)
描述:choice() 方法返回一個列表,元組或字符串的隨機項。
語法
1 2 | import random random.choice(x) |
參數(shù):
x -- list,tuple,strings的一種
實例演示
1 2 3 4 5 6 | >>> print random.choice(( 'a' , 'be' , 5 , 'e' )) 5 >>> print random.choice([ 10 , 2 , 6 , 5 , 85 , 'af' ]) 85 >>> print random.choice( 'i love python' ) v |
6. sample()函數(shù)
描述:sample()方法返回隨機從列表,元組或字符串其中部分隨機項 ;返回類型為元組類型
語法
1 2 | import random random.sample(x,n) |
參數(shù):
x -- list,tuple,strings的一種
n -- 返回n個隨機項
實例演示
1 2 3 4 5 6 | >>> print random.sample( 'i love python' , 3 ) [ ' ' , 'e' , 'i' ] >>> print random.sample([ 10 , 20 , 50 , 23 , 'ab' ], 3 ) [ 50 , 'ab' , 23 ] >>> print random.sample(( 10 , 20 , 50 , 23 , 'ab' ), 3 ) [ 50 , 20 , 'ab' ] |
7. shuffle()函數(shù)
描述:shuffle() 方法將序列的所有元素隨機排序。類似于洗牌
語法 :
1 2 | import random random.shuffle(x) |
參數(shù):
x -- list,tuple的一種;python2.x只支持list類型
實例演示
1 2 3 4 | >>> list = [ 'a' , 'b' , 'c' , 'd' , 'e' ]; >>> random.shuffle( list ); >>> print list ; [ 'c' , 'd' , 'a' , 'e' , 'b' ] |
拓展:將元祖反轉(zhuǎn);實現(xiàn)reverse函數(shù)的效果
1 2 3 4 | >>> list = [ 'a' , 'b' , 'c' , 'd' , 'e' ]; >>> list1 = list [:: - 1 ] >>> print list1 [ 'e' , 'd' , 'c' , 'b' , 'a' ] |
售前咨詢
售后咨詢
備案咨詢
二維碼
TOP