通过一系列运算符进行迭代 [英] Iterate through a sequence of operators

查看:71
本文介绍了通过一系列运算符进行迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以/是否可以像下面的示例中那样通过一系列的运算符进行迭代?

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

这篇关于通过一系列运算符进行迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆