2012-09-21 32 views
2

我寫了這樣的功能,op給出了操作牌子,上面像'+','-','*','/'以上,代碼「增加了」一切使用給定的運營商,如何「增加」的東西放在一起蟒蛇

下面是代碼:

def arithmetic(op,*args): 
    result = args[0] 
    for x in args[1:]: 
     if op =='+': 
      result += x 
     elif op == '-': 
      result -= x 
     elif op == '*': 
      result *= x 
     elif op == '/': 
      result /= x 
    return result 

有沒有一種方法我可以直接使用的+,-,*,/?所以我不必寫一個If-Else語句?

+2

通常情況下,最簡單的方法,以避免'如果/ elif'子句是使用字典。 :) – mgilson

回答

3

我認爲你正在尋找的內置reduce功能與operator結合:

import operator 
a = range(10) 
reduce(operator.add,a) #45 
reduce(operator.sub,a) #-45 
reduce(operator.mul,a) #0 -- first element is 0. 
reduce(operator.div,a) #0 -- first element is 0. 

當然,如果你想做到這一點使用字符串,您可以映射字符串使用字典的操作:

operations = {'+':operator.add,'-':operator.sub,} # ... 

則變爲:

reduce(operations[your_operator],a) 
+1

...並使用類似'{'+':operator.add,...}' – eumiro

10

你可以使用相應的operators

import operator 
def arithmetic(opname, *args): 
    op = {'+': operator.add, 
      '-': operator.sub, 
      '*': operator.mul, 
      '/': operator.div}[opname] 
    result = args[0] 
    for x in args[1:]: 
     result = op(result, x) 
    return result 

或縮短,reduce

import operator,functools 
def arithmetic(opname, arg0, *args): 
    op = {'+': operator.add, 
      '-': operator.sub, 
      '*': operator.mul, 
      '/': operator.div}[opname] 
    return functools.reduce(op, args, arg0) 
1

對於+運營商,你有內置sum功能。

-1

您可以使用EXEC:

def arithmetic(op, *args): 
result = args[0] 
for x in args[1:]: 
    exec('result ' + op + '= x') 
return result 
+1

Argv!不要鼓勵這種行爲... – mgilson

+0

這是真的,對不起:( – rebeco