繁体   English   中英

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

[英]Python if-statement with variable mathematical operator

我正在尝试将变量数学运算符插入到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失败SyntaxError: invalid syntax 我已经尝试过使用exec和eval但是在if语句中都没有工作,我有什么选择来解决这个问题?

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

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"

使用operator模块:

import operator
op = operator.eq

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

我已经尝试过使用exec和eval,但是在if语句中都没有

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

maths_operator = "=="

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

或执行该行:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM