Python中的if语句与变量数学运算符

18

我正在尝试将一个可变的数学运算符插入到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 语句中都无法工作,那么我有什么其他选择可以解决这个问题呢?

3个回答

21
使用operator模块和字典一起查找运算符的文本等效项。为了保持一致,所有这些运算符必须是一元或二元运算符。
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"

15

使用operator模块:

import operator
op = operator.eq

if op("test", "test"):
   print "match found"

1
感谢你的回答,马克。operator模块def是解决这个问题的方法。 - binhex

1
我尝试过使用exec和eval,但在if语句中都不起作用。
为了完整起见,应该提到它们确实可以工作,即使发布的答案提供了更好的解决方案。您必须对整个比较进行eval(),而不仅仅是运算符:
maths_operator = "=="

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

或者执行以下命令:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接