Python 如何";加上「;把东西放在一起

Python 如何";加上「;把东西放在一起,python,Python,我写了一个这样的函数,op给出了一个像“+”、“-”、“*”、“/”或更多的运算符号,代码“添加”所有使用给定运算符的东西 代码如下: def arithmetic(op,*args): result = args[0] for x in args[1:]: if op =='+': result += x elif op == '-': result -= x elif op == '*':

我写了一个这样的函数,
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语句

我想您正在寻找内置的
reduce
功能与
操作符相结合:

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.
当然,如果要使用字符串执行此操作,可以使用dict将字符串映射到操作:

operations = {'+':operator.add,'-':operator.sub,} # ...
然后它变成:

reduce(operations[your_operator],a)

您可以使用相应的:

或更短,带有:


对于
+
运算符,您具有内置的
求和功能。

您可以使用exec:

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

…并且经常使用类似于
{'+':operator.add,…}
的东西,避免使用
if/elif
子句的最简单方法是使用字典。:)
import operator,functools
def arithmetic(opname, arg0, *args):
    op = {'+': operator.add,
          '-': operator.sub,
          '*': operator.mul,
          '/': operator.div}[opname]
    return functools.reduce(op, args, arg0)
def arithmetic(op, *args):
 result = args[0]
 for x in args[1:]:
   exec('result ' + op + '= x')
 return result