【问题标题】:Python if-statement with variable mathematical operator具有可变数学运算符的 Python if 语句
【发布时间】:2012-08-04 13:12:19
【问题描述】:

我正在尝试将变量数学运算符插入到 if 语句中,这是我在解析用户提供的数学表达式时尝试实现的示例:

maths_operator = "=="

if "test" maths_operator "test":
       print "match found"

maths_operator = "!="

if "test" maths_operator "test":
       print "match found"
else:
       print "match not found"

显然以上失败了SyntaxError: invalid syntax。我尝试过使用 exec 和 eval,但在 if 语句中都不起作用,我有什么选项可以解决这个问题?

【问题讨论】:

    标签: python parsing if-statement operators mathematical-expressions


    【解决方案1】:

    使用操作符包和字典来根据它们的文本等价物查找操作符。所有这些都必须是一元或二元运算符才能始终如一地工作。

    import operator
    ops = {'==' : operator.eq,
           '!=' : operator.ne,
           '<=' : operator.le,
           '>=' : operator.ge,
           '>'  : operator.gt,
           '<'  : operator.lt}
    
    maths_operator = "=="
    
    if ops[maths_operator]("test", "test"):
        print "match found"
    
    maths_operator = "!="
    
    if ops[maths_operator]("test", "test"):
        print "match found"
    else:
        print "match not found"
    

    【讨论】:

      【解决方案2】:

      使用operator 模块:

      import operator
      op = operator.eq
      
      if op("test", "test"):
         print "match found"
      

      【讨论】:

      • 感谢您的回答马克,操作员模块 def 是解决这个问题的方法。
      【解决方案3】:

      我尝试过使用 exec 和 eval,但在 if 语句中都不起作用

      为了完整起见,应该提到它们确实有效,即使发布的答案提供了更好的解决方案。您必须 eval() 整个比较,而不仅仅是运算符:

      maths_operator = "=="
      
      if eval('"test"' + maths_operator '"test"'):
             print "match found"
      

      或执行该行:

      exec 'if "test"' + maths_operator + '"test": print "match found"'
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-06-20
        • 2018-12-08
        • 2019-06-05
        • 2022-01-09
        • 2015-02-08
        • 2015-12-25
        • 1970-01-01
        相关资源
        最近更新 更多