2016-10-31 45 views
1

我想根據字符串的上下文替換比較標記。我在Python 3.5上進行了PyQt5實驗。Python比較評估器替換

例如:

line = "<" 

if 1 line 2: 
    print("False") 

有沒有簡單的方法來做到這一點?我考慮使用一個測試案例:

if line == "<": 
    if 1 < 2: 
     print("False") 

等等,但這會變得很長,尤其是對於迭代的「if」語句。 例:

if pt1 < pt1_target: 
    if pt2 > pt2_target: 
     etc. 

或者,如果這是不可能的,沒有任何人有任何解決方案,以避免大規模的,包羅萬象的「如果」,每個分支語句塊?我打算放一點指令,這樣line最終代替了正確的python等價物,例如"="而不是正確的"=="

在此先感謝!

+1

檢查也[如何傳遞一個運算符到一個python函數?](http://stackoverflow.com/questions/18591778/how-to-pass-an-operator-to-a-python-function),[賦值運算符到變量在Python中?](http://stackoverflow.com/questions/2983139/assign-operator-to-variable-in-python) – user2314737

回答

3

operator模塊使用的功能:

from operator import eq, ne, lt, le, gt, ge 

operator_functions = { 
    '=': eq, 
    '!=': ne, 
    '<': lt, 
    '<=': le, 
    '>': gt, 
    '>=': ge, 
} 

operator = # whatever 

if operator_functions[operator](a, b): 
    do_whatever() 
+0

是''=':eq'在purpuse上,說那些沒有遵守標準的Python操作符語法? –

+1

@tobias_k:這是故意的,因爲它聽起來像是使用'='而不是'=='輸入的問題。我可能應該對此發表評論或其他內容。 – user2357112

+0

@ user2357112我喜歡這樣,我不必爲操作員需要的樣子添加說明,即自然的「=」作品。謝謝! – MadisonCooper

2

您可以使用字典來操作字符串映射到相應的功能operator模塊:

import operator 

ops = {'>': operator.gt, 
     '<': operator.lt, 
     '==': operator.eq, 
     # etc... 
     } 

op_string = '<' 
if ops[op_string](1, 2): 
    print('True') 
# or this... 
print(ops[op_string](1, 2)) 

注意,這個例子打印True。你舉的例子似乎否定的邏輯性,比如1 < 2將評估爲False - 如果這就是你想要的東西,然後就可以在邏輯開關:

if ops[op_string](1, 2): 
    print 'False' 
# or this... 
print(not ops[op_string](1, 2)) 

或者你可以改變經營者的映射:

ops = {'<': operator.ge, ...} 
print(ops[op_string](1, 2)) 
# False