【问题标题】:How can I draw from a list of math operators and have it interpreted as a math operation and not a string? [duplicate]如何从数学运算符列表中提取并将其解释为数学运算而不是字符串? [复制]
【发布时间】:2020-11-23 16:47:00
【问题描述】:

我正在尝试使用此循环来压缩现有代码,但将运算符存储在列表中然后从中提取不起作用,它会引发此错误:TypeError: unsupported operand type(s) for +: 'float' and 'str'

我知道它没有将operator 变量解释为实际的数学运算,而是将其读取为str,但我不知道如何解决这个问题。这是我构建的完整循环。

operators = ["+", "-", "*", "/", "^"]

for operator in operators:
    math_expression = input("Enter your math expression, or (q)uit: ")
    print("Operator found " + operator)
    operator_position = math_expression.find(operator) # find operator
    print("Found " + operator + "operator at index " + str(operator_position))
    first_number = math_expression[:operator_position] # find first number
    second_number = math_expression[operator_position + 1:] # find second number
    answer = float(first_number) + operator + float(second_number)

【问题讨论】:

  • 您正在尝试的内容相当于1.5 + "*" + 0.5 之类的内容,这只会导致该错误,因为您正在尝试将浮点数与字符串连接起来。你可以使用evalexec 之类的东西,你试过了吗?仅当您不想创建安全的东西时才应使用它们。
  • 不要使用evalexec!它们可用于执行任意代码。
  • @RandomDavis 我没试过,我会研究一下,谢谢!
  • 创建一个 mapping (即一个字典)从字符串到一个执行你想要的任何操作的函数。例如{"+": lambda x,y: return x+y, "-": lambda x,y: x - y, ...},或者使用import operator,可以使用{"+": operator.add, "-": operator.sub, ...}
  • @aidenmitchell 很好,因为“正确地”创建一个计算器很复杂。它至少涉及为您要处理的输入字符串编写解析器。当然,您可以使用使用 Python 解析器的 evalexec,但如上所述,通常您希望避免来自用户输入的 evaling 字符串,这是非常不安全的

标签: python python-3.x list loops


【解决方案1】:

operator 模块具有代表基本操作的函数,例如您要查找的函数。

我们来了

  • 将这些运算符填充到字典中
  • 循环遍历每个运算符的 symbolfunction
  • 如果在用户输入中找到符号,str.partition() 函数会将字符串拆分为符号前后的段...
  • 然后我们只需拨打function。
import operator

operators = {
    "+": operator.add,
    "-": operator.sub,
    "*": operator.mul,
    "/": operator.truediv,
    "^": operator.pow,
}

expression = "5 + 3"  # elided input to make debugging faster

for symbol, func in operators.items():
    if symbol in expression:
        a, _, b = expression.partition(symbol)
        answer = func(float(a), float(b))
        print(answer)
        break

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-11
    • 1970-01-01
    • 1970-01-01
    • 2019-07-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多