🍖random 模塊

引入

1.什麼是 random 模塊

  • random 模塊是 Python的內置模塊
  • random 主要用來生成隨機數

random 模塊常見用法

1.random( )

  • 只能生成大於 0 且小於 1 之間的小數 (float類型)
import random

print(random.random())  # 0.9449282236205908
print(random.random())  # 0.297501908739908

2.uniform( )

  • 生成指定數值之間的小數 (float)
import random

print(random.uniform(2,5))  # 3.641231407326168
print(random.uniform(2,5))  # 3.0820775843719668

3.randint( )

  • 生成指定數值之間的整數 (int類型)
import random

⛅生成大於等於 2 且小於等於 5 之間的整數
print(random.randint(2,5))  # 4
print(random.randint(2,5))  # 2
print(random.randint(2,5))  # 5

4.randrange( )

  • 生成指定數值之間的整數 (顧頭不顧尾)
import random

⛅生成大於等於 2 且小於 5 之間的整數
print(random.randrange(2,5))  # 3
print(random.randrange(2,5))  # 2
print(random.randrange(2,5))  # 3

5.choice( )

  • 從你指定的列表裏面隨機取出一個值
import random

res = random.choice([1,'23',[4,5]])
print(res,type(res))
'''屢次輸出後的結果
23     <class 'str'>
1      <class 'int'>
[4, 5] <class 'list'>
'''

6.sample( )

  • 從你指定的列表裏面隨機取出你指定個數的元素組合
import random

res = random.sample([1,2,3,'23',[4,5]],2)  # 從列表裏隨機取出 2 個元素組合
print(res,type(res))  # [3, 2] <class 'list'>  (存放在一個列表裏)

res = random.sample([1,2,3,'23',[4,5]],3)  # # 從列表裏隨機取出 3 個元素組合
print(res,type(res))  # ['23', [4, 5], 2] <class 'list'>

7.shuffle( )

  • 將列表裏面元素的順序打亂, 至關於洗牌 (只能傳入列表)
import random

item = [1,2,3,4,5]
random.shuffle(item)
print(item)  # [4, 1, 3, 5, 2]

隨機生成碼實現

1.儲蓄知識

  • 小寫字母 a-z 對應的十進制是 97-122
  • 大寫字母 A-Z 對應的十進制是 65-90
  • chr(num) : 將傳入的一個十進制轉換成對應的 ASCII 碼錶中的一個字符
  • ord('A-z') : 將傳入的一個 ASCII 碼中的一個字符轉換成對應的十進制

2.生成指定位數的驗證碼, 含大小寫英文和數字

import random

def auth_code(count=6):
    res = ''
    for i in range(count):
        lower = chr(random.randint(97,122))  # 隨機小寫字母
        upper = chr(random.randint(65,90))   # 隨機大寫字母
        num = str(random.randint(0,9))       # 隨機數字
        res2 = random.choice([lower,upper,num])  # 三者之間隨機取走一個
        res += res2  # 字符拼接
    return res

print(auth_code(6))  # Fr58Vg
print(auth_code(6))  # v0IOY8
print(auth_code(6))  # I9Z2gf
print(auth_code(6))  # J9128t

3.優化版本

  • 上一個版本是字符拼接, 會重複新建內存空間, 形成必定的資源佔用
  • 優化版本使用列表來接收值, 內存空間不重複申請, 再使用 join 將列表拼成字符串
import random

def auth_code(count=6):
    l = []
    for i in range(count):
        lower = chr(random.randint(97, 122))
        upper = chr(random.randint(65,90))
        num = str(random.randint(0,9))
        res2 = random.choice([lower,upper,num])
        l.append(res2)
    return "".join(l)

print(auth_code())  # MSlAum
print(auth_code())  # J954pz
print(auth_code())  # Y9z9Mz
print(auth_code())  # 5QQJo4
相關文章
相關標籤/搜索