所以我希望它从列表中选择一个随机数字 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)
您可能希望使用random.shuffle()
来混合字符,而不是按顺序排列它们:
from random import sample as sp
from random import shuffle as sh
lower_case = 'abcdefghijklmnopqrstuvwxyz'
upper_case = lower_case.upper()
numbers = '1234567890'
punctuation = '!@#$%^&*('
ready_password = sp(lower_case,2)+sp(upper_case,2)+sp(punctuation,2)+sp(numbers,2)
sh(ready_password)
print(''.join(ready_password))
输出:
c3D#0hV%
sample()
需要 2 个参数,第二个是要返回的列表长度,但我认为您要做的是使用shuffle()
,对所有随机选择的字符重新排序(示例不会打乱列表(。更改此行
ready_password = random.sample(password_not_ready)
自
ready_password = random.shuffle(password_not_ready, len(password_not_ready))
有关详细信息,请参阅随机播放和示例文档。
K=8 表示 8 位密码
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, k=8)
print(ready_password)
根据您的要求- 如果要使用random.sample
则需要传递第二个参数 k(来自password_not_ready
的随机样本的长度。 所以使用
ready_password = random.sample(password_not_ready, k) #k is the desire length of the sample
print(ready_password)
使用您现有的代码应该可以工作。
友情链接 - https://www.geeksforgeeks.org/python-random-sample-function/https://docs.python.org/3/library/random.html