Python攻克之路-random模块
random模塊
描述:生成隨機(jī)數(shù)
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對(duì)序列進(jìn)行選擇
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隨機(jī)選
In [32]: random.sample([[5,6],8,[1,2],9],2) #2是指定個(gè)數(shù) 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數(shù)字轉(zhuǎn)換字母
描述:ASCII對(duì)照表有數(shù)和字母的對(duì)應(yīng)
驗(yàn)證碼函數(shù)的實(shí)現(xiàn)
思路:a.生成一個(gè)5位的驗(yàn)證碼,包含隨機(jī)的數(shù)字和字母,定義一個(gè)空的變量code,向code添加隨機(jī)數(shù)字和字母
? ?b.使用for循環(huán)來(lái)添加for i in range(5),5是指定一個(gè)幾位數(shù),循環(huán)出一個(gè)5位數(shù)
? ?c.關(guān)鍵是生成任意數(shù),數(shù)字由random.randrange(10)
? ?d.把內(nèi)容添加在一起code+=str(add_code),相當(dāng)于生成一個(gè)數(shù)添加到code
? ?e.chr(random.randrange(65,91))字母的產(chǎn)生
? ? ? ? f.把數(shù)字和字母放進(jìn)一個(gè)列表中,使用random.choice來(lái)隨機(jī)選擇
轉(zhuǎn)載于:https://www.cnblogs.com/reid21/articles/8645035.html
總結(jié)
以上是生活随笔為你收集整理的Python攻克之路-random模块的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: cmake find_package 中
- 下一篇: Java 网络