[英]How do I optimize this random pass generator-ish?
初学者在这里,我尝试制作一个随机密码生成器,但我觉得有一种更有效的方法,请帮助,谢谢!
import random
x = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p',
'q', 'r', 's','t', 'u', 'v', 'w', 'x', 'y', 'z']
y = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p',
'q', 'r', 's','t', 'u', 'v', 'w', 'x', 'y', 'z']
z = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0']
for i in range(len(y)):
y[i] = y[i].upper()
g = 1
while g == 1:
a = random.choice(x)
b = random.choice(y)
c = random.choice(z)
d = random.choice(x)
e = random.choice(y)
f = random.choice(z)
h = random.choice(x)
i = random.choice(y)
j = random.choice(z)
k = random.choice(x)
l = random.choice(y)
m = random.choice(z)
n = random.choice(x)
o = random.choice(y)
p = random.choice(z)
break
print(a+b+c+d+e+f+h+i+j+k+l+m+n+o+p)
首先,简化您的字符串创建:
import string
# this will give you all upper and lower case letters and numbers 0-10
all_chars = string.ascii_letters + string.digits
然后,只需用户random.choice
在all_chars
范围内:
# the length of your string will be range(x) - 1
print(''.join(random.choice(all_chars) for i in range(10)))
输出:
bHGsT5swSv
所以完整的代码:
import string
import random
all_chars = string.ascii_letters + string.digits
# 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
# 9 character output
print(''.join(random.choice(all_chars) for i in range(10)))
# or as suggested by the comments using unpacking
print(*random.choices(all_chars, k=10), sep='')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.