有没有办法在python中使用中缀运算符(如+,-,*,/)作为高阶函数,而不创建“包装”函数?
def apply(f,a,b):
return f(a,b)
def plus(a,b):
return a + b
# This will work fine
apply(plus,1,1)
# Is there any way to get this working?
apply(+,1,1)发布于 2013-06-10 23:47:47
您可以使用operator模块,它已经为您编写了“包装器”函数。
import operator
def apply(f,a,b):
return f(a,b)
print apply(operator.add,1,1)结果:
2您还可以使用lambda函数定义包装器,这样就省去了使用独立def的麻烦
print apply(lamba a,b: a+b, 1, 1)发布于 2013-06-10 23:49:38
使用运算符模块和字典:
>>> from operator import add, mul, sub, div, mod
>>> dic = {'+':add, '*':mul, '/':div, '%': mod, '-':sub}
>>> def apply(op, x, y):
return dic[op](x,y)
...
>>> apply('+',1,5)
6
>>> apply('-',1,5)
-4
>>> apply('%',1,5)
1
>>> apply('*',1,5)
5请注意,您不能直接使用+、-等,因为它们在python中不是有效的标识符。
发布于 2013-06-10 23:48:13
您可以这样使用operator模块:
import operator
def apply(op, a, b):
return op(a, b)
print(apply(operator.add, 1, 2))
print(apply(operator.lt, 1, 2))输出:
3
True另一种解决方案是使用lambda函数,但是“应该有1个,最好只有一个--显而易见的方法”,所以我更喜欢使用operator模块
https://stackoverflow.com/questions/17027805
复制相似问题