map()lambda()仅支持python 2.7.6的操作数

时间:2018-02-16 22:30:26

标签: python dictionary lambda operand

我在最后的手段寻求帮助,我的代码问题让我发疯。 我在Ubuntu 14.04上使用Python 2.7.6和Python 3.4.3,并使用以下非常简单的代码部分password generator urandom

import os


def random_password(length=20, symbols='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789@$^_+&'):
    password = []
    for i in map(lambda x: int(len(symbols)*x/255.0), os.urandom(length)):
        password.append(symbols[i])
    return ''.join(password)

random_password()

password = random_password()

print(password)

这部分代码适用于python 3.4.3。但每2或3次运行随机给出以下错误:

Traceback (most recent call last):
  File "/home/jsmith/Documents/PythonProjects/MainFile", line 12, in <module>
    IotaSeed = Gen_Seed()
  File "/home/jsmith/Documents/PythonProjects/MainFile", line 7, in Gen_Seed
    IotaSeed.append(symbols[i])
IndexError: string index out of range

使用Python 2.7.6,它根本不起作用并发出以下错误:

Traceback (most recent call last):
  File "PWDGEN.py", line 10, in <module>
    random_password()
  File "PWDGEN.py", line 6, in random_password
    for i in map(lambda x: int(len(symbols)*x/255.0), os.urandom(length)):
  File "PWDGEN.py", line 6, in <lambda>
    for i in map(lambda x: int(len(symbols)*x/255.0), os.urandom(length)):
TypeError: unsupported operand type(s) for /: 'str' and 'float'

我理解lambda和map是如何工作的但是我无法找到解决方案而且我无法切换到python 3.4.3,因为我用2.7编写了我的主程序。

我可以做些什么来使它在python 2.7下运行并避免&#34;字符串索引超出范围&#34;在3.4.3中看到错误?

谢谢,PGriffin。

1 个答案:

答案 0 :(得分:1)

int(len(symbols)*x/255.0)
len(symbols)时,

会产生x == 255。要解决这个问题,你可以将其除以256。但是,这不会给出均匀分布的随机字符,这对于密码生成是不可取的。请改用SystemRandom

import string
from random import SystemRandom


ALPHANUMERICS = string.ascii_letters + string.digits


def random_password(length=20, symbols=ALPHANUMERICS + '@$^_+&'):
    rng = SystemRandom()
    return ''.join(rng.choice(symbols) for _ in range(length))

比较每个字符在密码中出现的频率:

histogram not characteristic of a uniform distribution

之后:

histogram characteristic of a uniform distribution