Iterate through a sequence of operators

我只是一个虾纸丫 提交于 2019-12-10 10:54:56

问题


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.


回答1:


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)))



回答2:


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))



回答3:


Try this:

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

Hope this helps!



来源:https://stackoverflow.com/questions/34312846/iterate-through-a-sequence-of-operators

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!