新聞中心
這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
創(chuàng)新互聯(lián)Python教程:Python之random模塊詳解
python的random模塊

random模塊是python中一個生成隨機數(shù)的模塊。
random不是python解釋器內(nèi)置的模塊。
導入random模塊的方法是:
import random
如果只使用random模塊中的單個方法的話,也可以使用
from random import method_name
例如:
我只想生成一個10以內(nèi)的隨機的整數(shù),不需要random模塊的別的方法的時候,也可以使用以下命令
from random import randint random.randint(0,10)
查看random模塊的內(nèi)置方法可以使用以下命令:
dir(random)
其中常用的方法有下面幾個:
choice
#從一個非空列表中隨機選擇一個元素 >Choose a random element from a non-empty sequence.
>>> random.choice([1,3,5,7]) 1 >>> random.choice([1,3,5,7]) 3
相關(guān)推薦:《Python視頻教程》
randint
#從a和b(包括b)的范圍內(nèi)隨機生成一個整數(shù) >Return random integer in range [a, b], including both end points.
>>> random.randint(0,9) 8 >>> random.randint(0,9) 0 >>> random.randint(0,9) 4 >>> random.randint(0,9) 3
random
#生成一個0(包括0)到1內(nèi)的浮點數(shù) >random() -> x in the interval [0, 1).
>>> random.random() 0.3898009217264272 >>> random.random() 0.897328889551127 >>> random.random() 0.9899842422616898
randrange
#在指定范圍內(nèi)隨機生成一個整數(shù) > 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(100,200) 156 >>> random.randrange(100,200) 133 >>> random.randrange(10,20) 11 >>> random.randrange(10,20) 15
sample
#從一個列表或集合中隨機選擇多個元素 >Chooses k unique random elements from a population sequence or set.
>>> random.sample([23,[1,2,3],"aa","yy"],2) ['aa', 23] >>> random.sample([23,[1,2,3],"aa","yy"],3) ['aa', [1, 2, 3], 23]
shuffle
#把一個列表內(nèi)元素的順序打亂,列表的內(nèi)存地址不變 >Shuffle list x in place, and return None.
>>> l1=[1,"a",3,5,"b","c"] >>> id(l1) 140436582171208 >>> random.shuffle(l1) >>> print(l1) [1, 'b', 'a', 'c', 3, 5] >>> id(l1) 140436582171208
uniform
#在指定范圍內(nèi)隨機生成一個浮點數(shù) >Get a random number in the range [a, b) or [a, b] depending on rounding.
>>> random.uniform(12,33) 27.02416276339153 >>> random.uniform(12,33) 13.832414985007832 >>> random.uniform(12,33) 12.827493699496461
現(xiàn)在想生成一個5位包含大小寫和數(shù)字的隨機驗證碼,代碼如下:
import random def random_code(): random_str = "" for i in range(5): #隨機選擇一個整數(shù) num=random.randint(0,9) #生成一個大寫字母 upper=chr(random.randint(65,90)) #生成一個小寫字母 lower=chr(random.randint(97,122)) #每次從大小寫字母中隨機選擇一位 res=random.choice([str(num),upper,lower]) random_str+=res return random_str print(random_code())
運行5次這個程序,生成的驗證碼如下:
KwlTN t1Pag 294l6 t1Pag 294l6
名稱欄目:創(chuàng)新互聯(lián)Python教程:Python之random模塊詳解
轉(zhuǎn)載注明:http://www.dlmjj.cn/article/ccsgdcp.html


咨詢
建站咨詢
