日韩无码专区无码一级三级片|91人人爱网站中日韩无码电影|厨房大战丰满熟妇|AV高清无码在线免费观看|另类AV日韩少妇熟女|中文日本大黄一级黄色片|色情在线视频免费|亚洲成人特黄a片|黄片wwwav色图欧美|欧亚乱色一区二区三区

RELATEED CONSULTING
相關咨詢
選擇下列產品馬上在線溝通
服務時間:8:30-17:00
你可能遇到了下面的問題
關閉右側工具欄

新聞中心

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

python的random模塊

random模塊是python中一個生成隨機數的模塊。

random不是python解釋器內置的模塊。

導入random模塊的方法是:

import random

如果只使用random模塊中的單個方法的話,也可以使用

from random import method_name

例如:

我只想生成一個10以內的隨機的整數,不需要random模塊的別的方法的時候,也可以使用以下命令

from random import randint
random.randint(0,10)

查看random模塊的內置方法可以使用以下命令:

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

相關推薦:《Python視頻教程》

randint

#從a和b(包括b)的范圍內隨機生成一個整數
>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內的浮點數
>random() -> x in the interval [0, 1).
>>> random.random()
0.3898009217264272
>>> random.random()
0.897328889551127
>>> random.random()
0.9899842422616898

randrange

#在指定范圍內隨機生成一個整數
> 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

#把一個列表內元素的順序打亂,列表的內存地址不變
>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

    #在指定范圍內隨機生成一個浮點數
>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位包含大小寫和數字的隨機驗證碼,代碼如下:

import random
def random_code():
    random_str = ""
    for i in range(5):
        #隨機選擇一個整數
        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模塊詳解
網頁鏈接:http://www.5511xx.com/article/ccsgdcp.html