- 工信部備案號 滇ICP備05000110號-1
- 滇公網安備53011102001527號
- 增值電信業(yè)務經營許可證 B1.B2-20181647、滇B1.B2-20190004
- 云南互聯網協會理事單位
- 安全聯盟認證網站身份V標記
- 域名注冊服務機構許可:滇D3-20230001
- 代理域名注冊服務機構:新網數碼
- CN域名投訴舉報處理平臺:電話:010-58813000、郵箱:service@cnnic.cn
1. random()函數
描述:random() 方法返回隨機生成的一個實數,它在[0,1)范圍內。
語法:
1 2 | import randomrandom.random(); |
注意:random()是不能直接訪問的,需要導入 random 模塊,然后通過 random 靜態(tài)對象調用該方法。
實例演示:
1 2 3 4 5 | >>> import random>>> print random.random();0.803119901575>>> print random.random();0.451592468747 |
2. randrange()函數
描述: randrange() 方法返回指定遞增基數集合中的一個隨機數,基數缺省值為1。返回一個整數
語法
1 2 | import randomrandom.randrange ([start,] stop [,step]) |
參數:
start -- 指定范圍內的開始值,包含在范圍內
stop -- 指定范圍內的結束值,不包含在范圍內。
step -- 指定遞增基數
實例演示
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()函數
描述:randint()方法將隨機生成一個整數,它在[x,y]范圍內 ;有點等價于randrange(x,y+1).
語法
1 2 | import randomrandom.randint(x,y) |
參數:
x -- 指定范圍內的開始值,包含在范圍內
y -- 指定范圍內的結束值,包含在范圍內。
實例演示
1 2 3 4 | >>> print random.randrange(5,10);9>>> print random.randint(5,10);6 |
4. uniform()函數
描述:uniform() 方法將隨機生成下一個實數,它在[x,y]范圍內。返回一個浮點數
語法:
1 2 | import randomrandom.uniform (x,y) |
參數:
x -- 指定范圍內的開始值,包含在范圍內
y -- 指定范圍內的結束值,包含在范圍內。
實例演示
1 2 3 4 | >>> print random.uniform(5,10);9.13282585434>>> print random.uniform(9,10);9.95958315062 |
5. choice()函數
描述:choice() 方法返回一個列表,元組或字符串的隨機項。
語法
1 2 | import randomrandom.choice(x) |
參數:
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()函數
描述:sample()方法返回隨機從列表,元組或字符串其中部分隨機項 ;返回類型為元組類型
語法
1 2 | import randomrandom.sample(x,n) |
參數:
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()函數
描述:shuffle() 方法將序列的所有元素隨機排序。類似于洗牌
語法 :
1 2 | import randomrandom.shuffle(x) |
參數:
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'] |
拓展:將元祖反轉;實現reverse函數的效果
1 2 3 4 | >>> list=['a','b','c','d','e'];>>> list1=list[::-1]>>> print list1['e', 'd', 'c', 'b', 'a'] |
售前咨詢
售后咨詢
備案咨詢
二維碼

TOP