1. 程式人生 > >寫一個函式,隨機生成N條不重複的手機號

寫一個函式,隨機生成N條不重複的手機號

方法一:
import random def phone(count):
results = [] while len(results)!=count: starts = [138,156,130,170,188,189] start = random.choice(starts) end = random.randint(0,99999999) res = '%s%08d\n'%(start,end) # 格式化字串。%08d,獲取8位的數字,並換行 if res not in results: # 迴圈遍歷列表,不在列表中,就新增對應的號碼到列表 results.append(res) with open(
'phone.txt','w') as fw: fw.writelines(results) phone(100)

 

方式二:

import random
import string

def email(count):
    if count<1:
        print('count不能小於1')
        return
    emails = set()
    while len(emails)!=count:
        email_len = random.randint(6,12)
        email_end 
= ('@163.com', '@qq.com', '@sina.com', '@126.com') start = random.choice(string.ascii_uppercase)+\ random.choice(string.ascii_lowercase)\ + random.choice(string.digits)+random.choice(string.punctuation) other_len = email_len - 4 #剩餘字串的長度 other = random.sample(string
.digits+string.ascii_letters+string.punctuation,other_len) res = other + list(start) random.shuffle(res) end = random.choice(email_end) email = ''.join(res)+end+'\n' emails.add(email) with open('email.txt','w') as fw: fw.writelines(emails)