python隨機產生手機號、數字

來源:互聯網
上載者:User

python隨機產生手機號、數字。代碼如下:

#  -*- coding:gbk -*-import random#隨機產生26個手機號:以13開頭,後面跟一位4~9之間的任意一位元字,後面是8位隨機數字for _ in range(26):    print('13' +          str(random.randrange(4,10))+          ''.join( str(random.choice(range(10))) for _ in range(8) )          )#隨機產生26個數字:產生一個0~1之間的隨機小數,乘1000,四捨五入到小數後3位,加上隨機產生的30~59之間的數字#由於sample函數返回的結果是list類型的,這裡通過[0]取出第1個值for i in range(26):    print( round(random.random()* 1000,3 ) + random.sample(range(30,60,3),2)[0] )

函數簡介:

(1)randrange:這個函數會產生範圍是4~9之間的任意一個數字,注意不包含10.

>>> random.randrange(5)2>>> random.randrange(1,5)1

(2)choice: 資料來源是range(10),也就是從0~9之間隨機播放一個數字,多次調用可能產生重複值

>>> random.choice(['a','b','c','d','e'])'b'>>> random.choice(['a','b','c','d','e'])'d'>>> random.choice(['a','b','c','d','e'])'c'>>> random.choice(['a','b','c','d','e'])'b'

(3)random:產生從0~1之間的隨機小數

>>> import random>>> random.random()0.7379992978183179>>> random.random()0.4720995823183177
(4)sample:資料來源是range(30,60,3),從30~59之間(步進是3),也就是30、33、36。。。這樣的數字中,選擇2個,這2個數字不會重複

>>> random.sample(['a','b','c','d','e'],2)['d', 'b']>>> random.sample(['a','b','c','d','e'],2)['a', 'b']>>> random.sample(['a','b','c','d','e'],2)['e', 'd']

其他函數:

(5)seed:要返回相同的隨機數,可以設定相同的種子

>>> random.seed(5)>>> random.random()0.6229016948897019>>> random.seed(5)>>> random.random()0.6229016948897019
(6)shuffle:隨機排列

>>> t=[0,1,2,3,4,5,6]>>> t[0, 1, 2, 3, 4, 5, 6]>>> random.shuffle(t)>>> t[5, 4, 2, 0, 6, 1, 3]


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.