2012-12-12 36 views
1

在評估條件時,是否可以將運算符包含在變量中?像這樣:用指向運算符的變量進行評估

>>> one = 1 
>>> two = 2 
>>> lessthan = '<' 

>>> if one lessthan two: print 'yes' 

有沒有辦法在表達式中返回變量?我也嘗試通過函數返回它。

def operator(op): 
    return op 

if one operator(lessthan) two: print 'yes' 

非常感謝,

回答

2

你可以使用operator

import operator 

lessthan = operator.lt 

one = 1 
two = 2 

if lessthan(one, two): 
    print 'yes' 

你也可以將字符串和操作之間的映射:

operators = { 
    '<': operator.lt, 
    '>': operator.gt, 
    '>=': operator.ge, 
    '<=': operator.le, 
} 

,然後調用函數:

>>> operators['<'](123, 456) 
True 
+0

這樣做!謝謝。 – puffin