2011-03-27 90 views
3

表達式的值可能重複:
python convert a string to an operator計算在Python

你好everyboby!

我剛開始學習Python並有一個簡單的問題。

是否有可能得到這個表達式的答案(計算)?

['10', '/', '5'] 

我的問題:我轉換'10''5'只是105。如何將'/'轉換爲/?我正在使用Python 2.7

+0

這是一個經典的功課行使。如果是這樣,標記它,如果它不是,那麼,這是一個值得注意的第一個練習:-) – tokland 2011-03-27 10:26:31

回答

1

我可以考慮的一種方法是將函數和存儲定義爲可以傳遞給操作符的字典。

代碼:

def div(x,y): 
    return x/y 

op_dict = { '/': div } 

a = [['10', '/', '5'], ['15','/','3']] 

answers = [ op_dict[x[1]](int(x[0]),int(x[2])) for x in a ] 

for answer in answers: 
    print answer 

結果:

2 
5 

擴展:

import operator 

op_dict = { '+': operator.add, 
      '-': operator.sub, 
      '/': operator.div, 
      '*': operator.mul} 


a = [['10', '/', '5'], ['15','*','3'], ['11','+','3']] 


answers = [ (x, op_dict[x[1]](int(x[0]),int(x[2]))) for x in a ] 

for answer in answers: 
    print answer 

個結果:

(['10', '/', '5'], 2) 
(['15', '*', '3'], 45) 
(['11', '+', '3'], 14) 
3
eval(''.join(['10', '/', '5'])) 

將上述溶液將工作的任何表達。例如:

eval(''.join(['10', '/', '5', '+', '3', '*', '2'])) 

唯一的問題是,EVAL是邪惡的...如果你想打一個表達式求你應該寫一個詞法,句法分析器,產生表達的AST,然後評估它。

+3

-10使用eval ..哦,等等,我只能做-1! – ThiefMaster 2011-03-27 09:25:56

+0

@ThiefMaster爲什麼使用eval評估表達式不好?這不正是它的目的嗎? – 2011-03-27 09:29:39

+2

@Paul Hankin。取決於,如果你正在評估的表達來自用戶輸入,它表示一個巨大的安全漏洞。 – 2011-03-27 09:31:10

5

我認爲最好的辦法是:

檢索列表的第一個元素,將它轉換成int

獲取第三個元素並將其轉換爲int

將第二個元素映射到函數以計算結果

import sys 

element = ['10', '/', '5'] 

operators = { 
    '/': lambda a, b: a/b, 
    '+': lambda a, b: a + b, 
    '-': lambda a, b: a - b, 
    '*': lambda a, b: a * b, 
} 

try: 
    a = int(element[0]) 
    b = int(element[2]) 
    result = operators[element[1]](a, b) 

    print result 
except: 
    sys.exit(1) 

正如ThiefMaster所說,您也可以使用操作員模塊。替換此:

operators = { 
    '/': lambda a, b: a/b, 
    '+': lambda a, b: a + b, 
    '-': lambda a, b: a - b, 
    '*': lambda a, b: a * b, 
} 

通過

import operator 
operators = { 
    '/': operator.div, 
    '+': operator.add, 
    '-': operator.sub, 
    '*': operator.mul, 
} 
1

要添加一些現有的答案,我們可以建立一個遞歸的評價只有一個多一點代碼:

import operator as op 

operations = {"+": op.add, "-": op.sub, "*": op.mul, "/": op.div} 

def evaluate(expression): 
    if isinstance(expression, list): 
    operand1, string_operation, operand2 = expression 
    return operations[string_operation](evaluate(operand1), evaluate(operand2)) 
    else: 
    return int(expression) 

print(evaluate(["10", "/", "5"])) # 2  
print(evaluate(["10", "/", ["3", "+", "2"]])) # 2