我们想要创建一个函数来生成随机密码,并使用 random.choice() 函数。我们希望选择是随机的,因此我们尝试使用字典来实现。以下是我们的代码:
def makepassword():
letter1 = ["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"]
letter2 = ["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"]
symbol1 = ["@", "#", "$", "%", "&", "*", "<", ">"]
symbol2 = ["@", "#", "$", "%", "&", "*", "<", ">"]
number1 = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
dict1 = {0: "letter1", 1: "letter2", 2: "symbol1", 3: "symbol2", 4: "number1"}
k = dict1.get(randint(0, 4))
l = dict1.get(randint(0, 4))
m = dict1.get(randint(0, 4))
print(k, l, m)
password = (choice(k) + choice(l) + choice(m))
print(password)
我们尝试使用字典来生成随机选择,但是在运行该函数时,我们发现结果与预期不同。我们希望选择是随机的,但是实际结果却是固定的,例如总是生成"letter1letter2number1"这样的密码。
2、解决方案
方法一
问题在于我们使用字典的方式不正确。我们在字典中存储的是列表的名称,而不是列表本身。因此,当我们使用 choice() 函数时,我们实际上是在选择列表的名称,而不是列表中的元素。
为了解决这个问题,我们需要将列表本身存储在字典中。以下是修改后的代码:
def makepassword():
letter1 = ["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"]
letter2 = ["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"]
symbol1 = ["@", "#", "$", "%", "&", "*", "<", ">"]
symbol2 = ["@", "#", "$", "%", "&", "*", "<", ">"]
number1 = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
dict1 = {0: letter1, 1: letter2, 2: symbol1, 3: symbol2, 4: number1}
k = dict1.get(randint(0, 4))
l = dict1.get(randint(0, 4))
m = dict1.get(randint(0, 4))
print(k, l, m)
password = (choice(k) + choice(l) + choice(m))
print(password)
现在,我们可以生成随机密码了。
方法二
还有一种解决方法是直接使用 random.choice() 函数来生成随机选择,而不需要使用字典。以下是修改后的代码:
def makepassword():
letter1 = ["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"]
letter2 = ["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"]
symbol1 = ["@", "#", "$", "%", "&", "*", "<", ">"]
symbol2 = ["@", "#", "$", "%", "&", "*", "<", ">"]
number1 = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
password = (choice(letter1) + choice(symbol1) + choice(number1))
print(password)
这种方法更加简单,并且可以达到同样的效果。

4544

被折叠的 条评论
为什么被折叠?



