带有变量数学运算符的Python if语句

bin*_*hex 16 python parsing if-statement operators mathematical-expressions

我正在尝试将变量数学运算符插入到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"
Run Code Online (Sandbox Code Playgroud)

显然上面的失败了SyntaxError: invalid syntax.我已经尝试过使用exec和eval但是在if语句中都没有工作,我有什么选择来解决这个问题?

Nat*_*han 18

将运算符包与字典一起使用,以根据文本等效项查找运算符.所有这些必须是一元或二元运算符才能始终如一地工作.

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"
Run Code Online (Sandbox Code Playgroud)


Mar*_*ers 16

使用operator模块:

import operator
op = operator.eq

if op("test", "test"):
   print "match found"
Run Code Online (Sandbox Code Playgroud)