jessicaxu

一、生成随机密码要实现的功能:

1、输入次数,输入多少次就产生多少条数据

2、要求密码必须包含大写字母、小写字母和数字,长度8位,不能重复

 

二、实现代码

import random,string
src = string.ascii_letters + string.digits
count = input(\'请确认要生成几条密码: \')
list_passwds = []
for i in range(int(count)):
    list_passwd_all = random.sample(src, 5) #从字母和数字中随机取5位
    list_passwd_all.extend(random.sample(string.digits, 1))  #让密码中一定包含数字
    list_passwd_all.extend(random.sample(string.ascii_lowercase, 1)) #让密码中一定包含小写字母
    list_passwd_all.extend(random.sample(string.ascii_uppercase, 1)) #让密码中一定包含大写字母
    random.shuffle(list_passwd_all) #打乱列表顺序
    str_passwd = \'\'.join(list_passwd_all) #将列表转化为字符串
    if str_passwd not in list_passwds: #判断是否生成重复密码
        list_passwds.append(str_passwd)
print(list_passwds)

 

三、利用集合的交运算实现

import random,string
passwds = []  #保存符合要求的密码
count = input(\'请确认要生成几条密码: \')
i = 0  #记录符合要求的密码个数
while i < int(count):
    passwd = set(random.sample(string.ascii_letters + string.digits,8)) #从字母和数字中随机抽取8位生成密码
    if passwd.intersection(string.ascii_uppercase) and passwd.intersection(string.ascii_lowercase) and passwd.intersection(string.digits): #判断密码中是否包含大小写字母和数字
        passwds.append(\'\'.join(passwd))  #将集合转化为字符串
        i += 1 #每生成1个符合要求的密码,i加1
print(passwds)

 

四、利用正则表达式实现

import re, random, string

count1 = int(input(\'请输入密码个数(必须大于0): \'))
i = 0
passwds = []
while i < count1:
    tmp = random.sample(string.ascii_letters + string.digits, 8)
    passwd = \'\'.join(tmp)
    if re.search(\'[0-9]\', passwd) and re.search(\'[A-Z]\', passwd) and re.search(\'[a-z]\', passwd):
        passwds.append(passwd)
        i += 1
print(passwds)

 

   

分类:

技术点:

相关文章:

  • 2022-12-23
  • 2022-01-18
  • 2021-07-23
  • 2022-01-24
  • 2022-01-15
猜你喜欢
  • 2021-07-02
  • 2021-10-06
  • 2021-12-03
相关资源
相似解决方案