【问题标题】:calculating the value of the expression in Python [duplicate]在Python中计算表达式的值[重复]
【发布时间】:2011-03-27 09:21:15
【问题描述】:

可能重复:
python convert a string to an operator

大家好!

我刚开始学习 Python,有一个简单的问题。

是否有可能得到这个表达式的答案(计算)?

['10', '/', '5']

我的问题:我将 '10''5' 转换为 105。如何将'/' 转换为/?我正在使用 Python 2.7

【问题讨论】:

  • 这是一个经典的家庭作业。如果是,请标记它,如果不是,那么,这是一个值得注意的第一个练习 :-)

标签: python list


【解决方案1】:

我认为最好的方法是:

检索列表的第一个元素并将其转换为 int

检索列表的第三个元素并将其转换为 int

将第二个元素映射到函数以计算结果

import sys

element = ['10', '/', '5']

operators = {
    '/': lambda a, b: a / b,
    '+': lambda a, b: a + b,
    '-': lambda a, b: a - b,
    '*': lambda a, b: a * b,
}

try:
    a = int(element[0])
    b = int(element[2])
    result = operators[element[1]](a, b)

    print result
except:
    sys.exit(1)

正如ThiefMaster所说,你也可以使用operator模块。替换这个:

operators = {
    '/': lambda a, b: a / b,
    '+': lambda a, b: a + b,
    '-': lambda a, b: a - b,
    '*': lambda a, b: a * b,
}

通过

import operator
operators = {
    '/': operator.div,
    '+': operator.add,
    '-': operator.sub,
    '*': operator.mul,
}

【讨论】:

    【解决方案2】:
    eval(''.join(['10', '/', '5']))
    

    上述解决方案适用于任何表达式。例如:

    eval(''.join(['10', '/', '5', '+', '3', '*', '2']))
    

    唯一的问题是 eval 是邪恶的......如果你想制作一个表达式评估器,你应该编写一个词法分析器,一个句法解析器,生成表达式的 AST,然后对其进行评估。

    【讨论】:

    • -10 用于使用 eval.. 哦等等,我只能做 -1!
    • @ThiefMaster 为什么使用 eval 评估表达式不好?这不正是它的用途吗?
    • @Paul Hankin。取决于,如果您正在评估的表达式来自用户输入,它代表一个巨大的安全漏洞。
    • OP 正在学习 python,所以我猜 eval'ing 会从中获得乐趣......
    • @Ioan Alexandru Cucu:这取决于它是桌面应用程序还是 Web 应用程序(安全问题)。额外:我们​​可以在加入和评估之前验证列表项。这比编写一个好的解析器要容易得多。
    【解决方案3】:

    operator module 包含表示运算符的函数:

    import operator
    # Now operator.div(a, b) is the same as a / b
    

    【讨论】:

      【解决方案4】:

      我能想到的一种方法是定义函数并存储,而不是存储到可以将运算符传递给的字典中。

      代码:

      def div(x,y):
          return x / y
      
      op_dict = { '/': div }
      
      a = [['10', '/', '5'], ['15','/','3']]
      
      answers = [ op_dict[x[1]](int(x[0]),int(x[2])) for x in a ]
      
      for answer in answers:
          print answer
      

      结果:

      2
      5
      

      扩展:

      import operator
      
      op_dict = { '+': operator.add,
                  '-': operator.sub,
                  '/': operator.div,
                  '*': operator.mul}
      
      
      a = [['10', '/', '5'], ['15','*','3'], ['11','+','3']]
      
      
      answers = [ (x, op_dict[x[1]](int(x[0]),int(x[2]))) for x in a ]
      
      for answer in answers:
          print answer
      

      结果:

      (['10', '/', '5'], 2)
      (['15', '*', '3'], 45)
      (['11', '+', '3'], 14)
      

      【讨论】:

        【解决方案5】:

        要为现有答案添加一些内容,我们可以使用更多代码构建一个递归评估器:

        import operator as op
        
        operations = {"+": op.add, "-": op.sub, "*": op.mul, "/": op.div}
        
        def evaluate(expression):
          if isinstance(expression, list):
            operand1, string_operation, operand2 = expression
            return operations[string_operation](evaluate(operand1), evaluate(operand2))
          else:
            return int(expression)
        
        print(evaluate(["10", "/", "5"])) # 2    
        print(evaluate(["10", "/", ["3", "+", "2"]])) # 2
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-08-30
          • 2023-01-27
          • 1970-01-01
          • 2012-01-02
          • 2015-05-14
          • 1970-01-01
          • 2022-11-22
          • 1970-01-01
          相关资源
          最近更新 更多