簡體   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