python3.6內建模組——random詳解
阿新 • • 發佈:2018-12-18
python內建模組random是用來生成隨機數的,在許多場合都能應用到,算是比較常見的一種模組吧,下面詳細介紹其具體用法。
基本用法
- 隨機生成浮點數:有兩種,一種沒有引數,預設是0~1,另一種可以指定隨機生成的浮點數範圍。
>>> random.random()
0.6448965915384378
>>> random.uniform(5,6)
5.1662895382835075
- 隨機生成指定範圍的整數:有兩種方法,第二種除了可以指定範圍,還可以指定步長。
>>> random.randint(1,10) 5 >>> random.randrange(1,10) 6 >>> random.randrange(1,10,2) 1
- 隨機生成指定樣式中的元素:樣式可以是字串、元組、列表。
random.choice((1,2,'a','b'))
2
>>> random.choice([1,2,3,4])
1
>>> random.choice("qwerty")
't'
- 隨機生成指定數目的指定樣式中的元素:樣式可以是字串、元組、列表、集合。
>>> random.sample("abcedf",2) ['c', 'e'] >>> random.sample((1,2,8,5,6),3) [6, 5, 2] >>> random.sample(['a','b','c','d','f'],2) ['f', 'd'] >>> random.sample({1,2,3,4,5},3) [2, 4, 3] >>>
- 將列表的元素的順序打亂:類似於生活中的洗牌,此方法返回值為空,將改變原來列表。
>>> item = [1,2,3,4,5,6,7]
>>> random.shuffle(item)
>>> print(item)
[3, 6, 4, 2, 7, 1, 5]
簡單實際應用
- 隨機生成六位數字驗證碼
import random def func(): captcha = '' for i in range(6): num = random.randint(0,9) captcha += str(num) return captcha captcha = func() print(captcha)
648215
- 隨機生成六位數字和區分大小寫字母混合的驗證碼
這裡我們要知道一點的是,在國際標準ASCII碼中規定了字元A~Z的ASCII值為65~90,a~z的ASCII值為97~122。python內建方法chr可以將對應的ASCII值轉換成對應的字元。
import random
def func():
captcha = ''
for i in range(6):
a = random.randint(1,3)
if a == 1:
num = random.randint(0,9)
captcha += str(num)
elif a == 2:
num = random.randint(65,90)
captcha += str(chr(num))
elif a == 3:
num = random.randint(97, 122)
captcha += str(chr(num))
return captcha
captcha = func()
print(captcha)
qLK77Y