日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

Python攻克之路-random模块

發布時間:2025/7/25 python 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Python攻克之路-random模块 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

random模塊
描述:生成隨機數

random常用方法
random

In [2]: random.random() #0-1之間 Out[2]: 0.2295625620781645

?

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對照表有數和字母的對應

In [42]: chr(65) Out[42]: 'A'In [43]: chr(77) Out[43]: 'M'In [44]: chr(90) Out[44]: '

  

驗證碼函數的實現
思路: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來隨機選擇

In [51]: def verification_code():...: code=''...: for i in range(5):...: add_code=random.choice([random.randrange(10),chr(random.randrange(65,91))])...: code+=str(add_code)...: print(code)...: In [52]: verification_code() UR6HOIn [53]: verification_code() 7F942In [54]: verification_code() 5C3DL

轉載于:https://www.cnblogs.com/reid21/articles/8645035.html

總結

以上是生活随笔為你收集整理的Python攻克之路-random模块的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。