首页 > 解决方案 > 我正在尝试使用 Python 3.7 制作密码生成器。我在网上搜索了如何使用 sample() 但对我来说它不起作用

问题描述

所以我希望它从列表中选择一个随机数字 2 次,然后将其混合在一起以获得密码。我希望 ready_password 打印一个列表并且它可以工作,但是它也打印 [] 和 ''。所以我决定把它做成一个元组,但我不知道如何混合一个元组。这是我得到的错误:

TypeError: sample() missing 1 required positional argument: 'k'

代码-

import random

lower_case = ['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']

upper_case = ['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']

numbers = ['1', '2', '3', '4', '5', '6', '7', '8', '9']

punctuation = ['!', '@', '#', '$', '%', '^', '&', '*', '(']

lower1 = random.choice(lower_case)
lower2 = random.choice(lower_case)

upper1 = random.choice(upper_case)
upper2 = random.choice(upper_case)

number1 = random.choice(numbers)
number2 = random.choice(numbers)

punctuation1 = random.choice(punctuation)
punctuation2 = random.choice(punctuation)

password_not_ready = (lower1 + lower2 + upper1 + upper2 + number1 + number2 + punctuation1 + 
punctuation2)

ready_password = random.sample(password_not_ready)

print(ready_password)
   

标签: pythonpython-3.xrandomsamplepassword-generator

解决方案


sample()接受 2 个参数,第二个是要返回的列表的长度,但是我认为您的意思是使用shuffle(), 重新排序所有随机选择的字符(样本不会打乱列表)。更改此行

ready_password = random.sample(password_not_ready)

ready_password = random.shuffle(password_not_ready, len(password_not_ready))

有关更多信息,请参阅shuffle示例文档。


推荐阅读