1. 程式人生 > >python模塊之random

python模塊之random

算法 lin 隨機驗證碼 clas amp dom 維護 class def

python的隨機數模塊為random模塊,可以產生隨機的整數或浮點數。但是這是偽隨機數,python解釋器會維護一些種子數,然後根據算法算出隨機數。linux維護了一個熵池,這個熵池收集噪音的信息,更接近真隨機數。

random

  1. 隨機產生0-1的浮點數,不包括1
import random
print(random.random())
# 運行結果 0.8517652068795716
  1. 隨機產生a-b的整數,包括a和b
import random
a = 1
b = 10
print(random.randint(a, b))
# 運行結果 4
  1. 隨機產生a-b,不包括a和b的整數
import random
a = 1
b = 10
print(random.randrange(a, b))
# 運行結果 7
  1. 指定一個範圍並指定需要產生的隨機個數
import random
print(random.sample([‘aa‘, [‘a‘, ‘b‘], 3, 4, 5], 2))
# 運行結果 [[‘a‘, ‘b‘], 5]
  1. 打亂列表的順序(返回None)
import random
ls = [1, 2, 3, 4, 5, 9, 11]
random.shuffle(ls)
print(ls)
# 運行結果 [1, 9, 2, 5, 4, 11, 3]
  1. 從給定的序列中隨機選一個
import random
print(random.choice([1,2,3,4,5,6]))
# 運行結果 2
  1. 從給定的序列中隨機選多個(包括1個,返回一個列表)
import random
print(random.choices((1,2,3,4,5,6,7), k=3))
# 運行結果 [6, 5, 5]
  1. 制作隨機驗證碼
import random
def get_verifycode(length):
    res = ‘‘
    for i in range(length):
        a = random.randint(0, 9)
        b = chr(random.randint(65, 90))
        c = chr(random.randint(97, 122))
        s = random.choice([a, b, c])
        res += s
     return res

python模塊之random