Python攻克之路-random模块
生活随笔
收集整理的這篇文章主要介紹了
Python攻克之路-random模块
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
random模塊
描述:生成隨機數
random常用方法
random
?
randint自定義范圍
In [3]: random.randint(1,9) #包括9 Out[3]: 3In [4]: random.randint(1,9) Out[4]: 3In [5]: random.randint(1,9) Out[5]: 7
choice對序列進行選擇
In [6]: random.choice('world') Out[6]: 'o'In [7]: random.choice('world') Out[7]: 'o'In [8]: random.choice('world') Out[8]: 'l'In [13]: random.choice(['122',3,[4,5]]) Out[13]: '122'In [14]: random.choice(['122',3,[4,5]]) Out[14]: [4, 5]In [15]: random.choice(['122',3,[4,5]]) Out[15]: [4, 5]In [16]: random.choice(['122',3,[4,5]]) Out[16]: 3
sample隨機選
In [32]: random.sample([[5,6],8,[1,2],9],2) #2是指定個數 Out[32]: [9, [5, 6]]In [33]: random.sample([[5,6],8,[1,2],9],2) Out[33]: [8, [1, 2]]In [34]: random.sample([[5,6],8,[1,2],9],2) Out[34]: [9, [1, 2]]
randrange ****
In [36]: random.randrange(1,3) #不包括3 Out[36]: 1In [37]: random.randrange(1,3) Out[37]: 1In [38]: random.randrange(1,3) Out[38]: 1In [39]: random.randrange(1,3) Out[39]: 2
chr數字轉換字母
描述:ASCII對照表有數和字母的對應
驗證碼函數的實現
思路:a.生成一個5位的驗證碼,包含隨機的數字和字母,定義一個空的變量code,向code添加隨機數字和字母
? ?b.使用for循環來添加for i in range(5),5是指定一個幾位數,循環出一個5位數
? ?c.關鍵是生成任意數,數字由random.randrange(10)
? ?d.把內容添加在一起code+=str(add_code),相當于生成一個數添加到code
? ?e.chr(random.randrange(65,91))字母的產生
? ? ? ? f.把數字和字母放進一個列表中,使用random.choice來隨機選擇
轉載于:https://www.cnblogs.com/reid21/articles/8645035.html
總結
以上是生活随笔為你收集整理的Python攻克之路-random模块的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: cmake find_package 中
- 下一篇: Java 网络