Python附加列表

时间:2015-03-20 22:27:09

标签: python list input

尝试更改列表,以便我可以生成密码

passwordlength=int(input('Enter how long you would like the password')) # The user input 

for x in range(0,passwordlength):         
       password=''.join(characters)                
       print(password)

这就是我现在正在使用的。字符是我用于我的列表。这给了我输入重复输入数字的列表。

每当我尝试使用附加到列表中时,我最终都会倒退

任何帮助将不胜感激

4 个答案:

答案 0 :(得分:2)

我认为random.sample可能是你想要的:

from random import sample

passwordlength = int(input('Enter how long you would like the password')) # The user input 


password = ''.join(sample(characters,passwordlength))

或者切片到passwordlength

password = ''.join(characters[:passwordlength]) 

要验证用户输入,我们可以使用try / except和while循环:

from random import sample

while True:
    try:
        password_length = int(input('Enter password length between 1-{}'.format(len(characters)))) # The user input
        if password_length > len(characters):
            print("Password is too long")
            continue
        password = ' '.join(sample(characters,password_length))
        break
    except ValueError:
         print("Please enter digits only")

如果您的角色列表中有内注,则需要mapstr才能加入。

password = ' '.join(map(str,sample(characters,password_length)))

答案 1 :(得分:0)

这里有一些是模拟设置。选择将从列表中随机选择一个项目

from random import choice

myaplha = #somelist of letters to choice from
password = int(input("Enter password length")):

passw = []
for i in range(password):
    passw.append(choice(myaplha))
print("".join(passw))

password = "".join([choice(myaplha) for i in range(int(input("Enter password length")))])
print(password)

答案 2 :(得分:0)

试试这样:

passwordlength=int(input('Enter how long you would like the password')) # The user input 
characters=['1','2','3','4','5','a','b','b']
password=[]
for x in range(0,passwordlength):         
       password.append(characters[x])                

print(''.join(password))

答案 3 :(得分:0)

对不起,但这个问题并不完全清楚。

以下是我在这里做出的假设:

  • passwordlength是一个整数,包含要截断的长度(在代码中)
  • 字符是您要用作密码的字符/数字列表。例如characters = [' 1',' 2' '一个' ,' c',' d']等。

我不明白你试图用for循环做什么?

我相信以下内容应该做你想要的。

密码='' .join(字符)[0:密码长度]