关于这个关于iterating through a sequence of operators的帖子,我也希望以相同的顺序处理一元运算符。我使用lambda函数来摆脱第二个参数,但在Python中是否有特殊用途的工具/库?
a, b = 5, 7
for op in [('+', operator.add), ('-', lambda x, y: operator.neg(x))]:
print("{} {} {} = {}".format(a, op[0], b, op[1](a, b)))
答案 0 :(得分:1)
只需分离二元和一元运算符的处理。
a, b = 5, 7
# binary ops
for op in [('+', operator.add), ('-', operator.sub]:
print("{} {} {} = {}".format(a, op[0], b, op[1](a, b)))
#unary ops
for op in [('-', operator.neg]:
print("{} {} = {}".format(op[0], a, op[1](a)))