写一个函数,随机生成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)

猜你喜欢

转载自www.cnblogs.com/lily-20141202/p/10055187.html