如何使用字典为random.choice()函数生成随机选择

时间:2017-03-23 19:50:07

标签: python dictionary random

我正在尝试创建一个使用random.choice函数生成随机密码的函数,但我也希望选择是随机的,我试图使用dict用于此目的,但没有得到所需的结果.. 我的代码是:

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)

如果我打印并检查k,l,m的值 我正在获取诸如letter1/letter2/symbol1/symbol2/number1之类的值,因此尝试在选择函数中使用这些值。

当我直接使用时:password=(choice(letter1)+choice(symbol1)+choice(number1))它可以正常工作。

那么如何使用Dictionary实现上述Choice函数。

3 个答案:

答案 0 :(得分:1)

dict1={0:letter1,1:letter2,2:symbol1,3:symbol2,4:number1}

您希望将实际列表存储在字典中,而不是列表的名称。这将允许你做你想做的事;在访问字典时使用列表。

请注意,random的模块会警告将其用于安全性:

  

警告不应将此模块的伪随机生成器用于安全目的。有关安全性或加密用途,请参阅机密模块。

它推荐secrets模块。它也有choice()方法。

答案 1 :(得分:1)

另一种方法(repl.it上的工作示例):

weights指定每种类型需要多少个。其余的是随机选择的。

length是生成密码的总长度

from random import randint, choice, shuffle
import string

def makepassword(length=8, weights=[1,1,1,1]):
    password_builder= []
    for index, weight in enumerate(weights):
      for _ in range(weight):
        password_builder.append(index)
    while len(password_builder) < length:
      password_builder.append(randint(0, len(weights) - 1))
    shuffle(password_builder)
    lowercase=string.ascii_lowercase
    uppercase=string.ascii_uppercase
    symbols=["@","#","$","%","&","*","<",">"]
    numbers=string.digits
    types=[lowercase,uppercase,symbols,numbers]
    print(password_builder)

    password = []

    for char_type in password_builder:
      password.append(choice(types[char_type]))

    print(''.join(password))

makepassword()

示例:

re9Bf6s#
qV7GCn0#
51zt7N>Z
&u7sYQ&0
5ZOF@m&u

答案 2 :(得分:0)

我认为您不需要dict,也请使用string模块:

import random
import string

symbols = ("@","#","$","%","&","*","<",">")
choices = (
    string.ascii_lowercase,
    string.ascii_uppercase,
    symbols,
    symbols,
    string.digits
)

def make_password(length):
    return ''.join(
        map(
            str,
            (
                random.choice(random.choice(choices))
                for _ in xrange(length)
            )
        )
    )

print(make_password(4))
print(make_password(10))
print(make_password(6))

输出:

J&@0
g8*o3$I4O*
@#$FQ<