【问题标题】:map() lambda() unsupported operand only with python 2.7.6map() lambda() 不支持的操作数仅适用于 python 2.7.6
【发布时间】:2018-02-16 22:30:25
【问题描述】:

我在万不得已的情况下寻求帮助,我的代码有问题,这让我发疯。 我在 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 下工作并避免在 3.4.3 中出现“字符串索引超出范围”错误?

谢谢,PGriffin。

【问题讨论】:

  • 也许只是修复"foo" / 12.34 ..? IE。确保有两个数字......并找出为什么违反了另一个数字的期望。
  • 它被违反了,因为在 Python 3 urandom 返回一个bytes 对象。当你迭代 bytes 时,你会得到 int's。在 Python 2 中,urandom 返回一个 str 对象。当您迭代时,您会得到每个字符(也是str 类型)。在 python 2 中,您需要调用 ord(x) 将每个字符转换为其对应的 int 值。
  • 索引超出范围错误来自您的问题中未包含的代码,因此我们无法为您提供帮助。
  • i 超过 67(symbols 的上限)时,它在 Python3 中失败。在我运行的少数测试中,始终是 68。
  • 所以,综上所述,Python 2 中的 lambda 应该是 lambda x: int((len(symbols)-1)*ord(x)/255.0), os.urandom(length)

标签: python dictionary lambda operand


【解决方案1】:
int(len(symbols)*x/255.0)

x == 255 时可能导致len(symbols)。要解决这个问题,您可以改为除以 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))

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

之后:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-04
    • 2019-08-21
    • 2013-12-08
    • 2018-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多