Iterate through a sequence of operators

2019-06-08 03:37发布

Is it possible/Is there a way to iterate through a sequence of operators as in the following example?

a, b = 5, 7
for op in (+, -, *, /):
    print(a, str(op), b, a op b)

One possible use case is the test of the implementation of various operators on some abstract data type where these operators are overloaded.

3条回答
ゆ 、 Hurt°
2楼-- · 2019-06-08 04:29

Try this:

a,b=5,7
for op in ['+','-','*','/']:
    exec 'print a' + op + 'b'

Hope this helps!

查看更多
等我变得足够好
3楼-- · 2019-06-08 04:30

You can create your own operations, then iterate through them.

def add(a, b):
    return a + b

def sub(a, b):
    return a - b

def mult(a, b):
    return a * b

def div(a, b):
    return a / b
a, b = 5, 7

operations = {'+': add,'-': sub, '*':mult, '/': div}
for op in operations:
    print(a, op, b, operations[op](a, b))
查看更多
叛逆
4楼-- · 2019-06-08 04:33

You can use the operator module.

for op in [('+', operator.add), ('-', operator.sub), ('*', operator.mul), ('/', operator.div)]:
    print("{} {} {} = {}".format(a, op[0], b, op[1](a, b)))
查看更多
登录 后发表回答