python random隨機模組

來源:互聯網
上載者:User

標籤:random模組   python隨機模組   python基礎   

一、random隨機數模組

1、取0-1之間隨機的浮點數

>>> import random         //匯入random模組

>>> random.random()       //random方法為取0-1之間的隨機浮點數

0.36983506915898345

那麼可不可以在指定範圍內取隨機浮點數呢?

>>> random.uniform(1,3)                //使用uniform方法

1.0276983956141716



2、取指定範圍內的隨機整數

>>> random.randint(1,3)           //小括弧中需要指定範圍,注意:這裡的1-3都能隨機取到(1,2,3)

1

>>> random.randrange(1,3)         //randrange是含頭不含尾,所以隨機取的值就是(1,2)

2

那能不能從列表或者字串中隨機取呢?

>>> random.choice("hello")        //使用choice方法來達到效果

'l'

>>> random.choice([1,2,3])

2


3、從序列中隨機取兩位

>>> random.sample("hello",2)      //括弧中要傳遞兩個參數

['e', 'h']

>>> random.sample("hello",2)

['o', 'l']


4、把列表中元素的順序打亂

>>> l1 = [1,2,3,4,5]

>>> random.shuffle(l1)     //使用shuffle方法可以把列表元素的順序打亂

>>> l1

[4, 2, 1, 5, 3]


小練習:使用random模組產生驗證碼

小知識:ASCII中65-90是A-Z的字母

import random

member = ""

for i in range(4):

  current = random.randrange(0,4)

  if current == i:

    tmp = chr(random.randint(65,90))

  else:

    tmp = random.randint(0,9)

  member += str(tmp)

print(member)


指令碼拆解:

  定義一個空變數用來接收隨機驗證碼,使用for迴圈迴圈數字,在迴圈內產生一個與之範圍相同的驗證碼,用隨機數和迴圈數字做匹配,如果配對成功輸出大寫字母,如果沒匹配上,輸出0-9之間的任意整數,最後把混合值賦值給初始的空變數。

python random隨機模組

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.