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