简体   繁体   English

Python二进制到一元函数

[英]Python binary to unary function

Following this thread about iterating through a sequence of operators , I want also to take care of unary operators in the same sequence. 遵循有关遍历一系列运算符的主题之后 ,我还希望按相同的顺序处理一元运算符。 I used a lambda function to get rid of the second argument but are there special purpose tools/libraries for that in Python? 我使用了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)))

Just separate the processing of binary and unary operators. 只需将二进制和一元运算符的处理分开即可。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM