random 需要import
random.choice(seq),可以是列表,字符串,元组
random.choice(string.ascii_lowercase) >>'u' random.choice('123') >> '3' random.choice([1,2,3]) >> 2
random.choices(string.ascii_lowercase, k=3)
>>['r', 'c', 'y']
random.randint(a,b) 返回a~b之间的整型数
random.randint(1,10)
>>5
random.randrange(a,b,c) 返回一个a~b,步长为c的数字
random.randrange(1,10,2)
>>3
random.sample(population, k) 返回一个无序的长度为k的list
1 random.sample(string.ascii_lowercase,k=4) 2 >>['n', 'p', 't', 'b'] 3 4 random.sample([1,2,3,4], 3) 5 >>[2, 1, 4] 6 7 random.sample(string.ascii_lowercase,4) 8 >>['j', 'f', 'r', 'd']
random.shuffle(list),将list乱序
a = [1,3,4,5,6]
random.shuffle(a)
a
>>[1, 6, 3, 4, 5]
例子:在文件中生成密码
1 import string 2 import random 3 4 5 def create_pwd(): 6 password = "" 7 temp_list = [] 8 t = random.randint(1, 3) 9 temp1 = random.choices(string.ascii_lowercase, k=t) 10 temp2 = random.choices(string.ascii_uppercase, k=t) 11 temp3 = random.choices(string.digits, k=t) 12 temp4 = random.choices(string.punctuation, k=2) 13 #temp1 = random.sample(string.ascii_lowercase, k=t)代替 14 temp_list.extend(temp1) 15 temp_list.extend(temp2) 16 temp_list.extend(temp3) 17 temp_list.extend(temp4) 18 random.shuffle(temp_list) # list乱序 19 for i in temp_list: 20 password += i 21 if len(password) < 6: 22 password = create_pwd() 23 return password 24 25 26 def count_pwd(num): 27 lines = [] 28 while num > 0: 29 # with open('1.tx', 'a+', encoding='utf-8') as f: 30 line = create_pwd() 31 lines.append(line) 32 num -= 1 33 lines = list(set(lines)) #通过集合保存密码,并转化成list,便于去重一样的密码 34 if len(lines) < num: 35 temp_length = num - len(lines) 36 t = count_pwd(temp_length, lines) 37 lines.extend(t) 38 else: 39 return lines 40 41 42 if __name__ == "__main__": 43 num = int(input("请输入要产生的密码条数:").strip()) 44 t = count_pwd(num) 45 with open('pwd.txt', 'a+', encoding='utf-8') as f: 46 for line in range(len(t)): 47 f.write(t[line] + ' ') 48 with open('pwd.txt', 'r', encoding='utf-8') as f: 49 print(f.read())