python random

使用random隨機數要導入模塊:網絡

import random

該模塊的經常使用方法有:dom

randomide

# 返回[0,1)之間的隨機浮點數
for num in range(0, 3):
    result = random.random()
    print(result)
'''
0.453381918309
0.786956553147
0.180587982868
'''

randint(m,n)編碼

# 返回[m,n]之間的隨機整數,注意 m <= n
for num in range(0, 3):
    result = random.randint(1, 10)
    print(result)
'''
4
10
8
'''

randrange(i, j, m)spa

# 返回 i 到 j 之間間隔爲 m 的隨機整數
for num in range(0, 3):
    result = random.randrange(1, 100, 2)
    print(result)
'''
43
81
77
'''

uniform(m,n)code

# 返回m到n之間的隨機浮點數
for num in range(0, 3):
    result = random.uniform(1.1, 5.4)
    print(result)
'''
1.86508996253
4.09362214254
5.30874741462
'''

choice(tab)orm

# 返回從序列tab中隨機選取一個元素
strTab = ['one', 'two', 'three', 'four', 'five']
for num in range(0, 3):
    result = random.choice(strTab)
    print(result)
'''
one
four
two
'''

shuffle(tab)blog

# 將序列中的元素順序打亂
numTab = [1, 3, 5, 6, 7]
newnumTab = random.shuffle(numTab) 
random.shuffle(numTab)
print(newnumTab)            # 無返回,故爲None
print(numTab)               # [3, 5, 6, 1, 7]

 

生成隨機數11位手機號碼的小Demo:索引

# -*- coding:utf-8 -*-
# __author__ = 'Code~'

import random

'''
隨機生成有效的11位手機號碼,簡要說明下:
前三位: 網絡識別號,好比移動,聯通,電信,號碼區段以下:
    電信:133,149,153,173,177,180,181,189,191,199
    聯通:130,131,132,145,155,156,166,171,175,176,185,186
    移動:134,135,136,137,138,139,147,150,151,152,157,158,159,172,178,182,183,184,187,188,198
中間四位: 地區編碼,每位的範圍爲[0,9]
最後四位:MDN號碼,即用戶被叫時,主叫用戶所需撥打的號碼,每位的範圍爲[0,9]

摘自:https://baike.baidu.com/item/%E6%89%8B%E6%9C%BA%E5%8F%B7%E7%A0%81/1417348?fr=kg_qa '''

# 網絡識別號列表
identyList = [
    # 電信
    [133,149,153,173,177,180,181,189,191,199],
    # 聯通            
    [130,131,132,145,155,156,166,171,175,176,185,186],
    # 移動     
    [134,135,136,137,138,139,147,150,151,152,157,158,159,172,178,182,183,184,187,188,198],
]

# 生成隨機號碼,count爲生成的個數
def createRandPhone(count=10):
    # 獲取前三位的隨機索引
    randIndex = random.randint(0, len(identyList)-1)
    # 隨機號碼生成個數
    for _ in range(0, count):
        firstStr = str(random.choice(identyList[randIndex]))
        lastStr = ''
        # 獲取後八位隨機字符
        for i in range(0, 8):
            lastStr = lastStr + random.choice("0123456789")
        print(u'隨機手機號爲: ' + firstStr + lastStr)

createRandPhone(5)

輸出: 隨機手機號爲: 18264939118
隨機手機號爲: 18814309809
隨機手機號爲: 17898265918
隨機手機號爲: 18845063333
隨機手機號爲: 18251223696
相關文章
相關標籤/搜索