Try following:
>>> op = lambda a, b: a + b
>>> result = op(5, 7)
>>> result
12
Вопрос
I'm developing a bunch of functions that have the same basic structure - they take two lists and use a loop to do a particular operation pairwise for the two lists (for example, one will take each element of a list raised to the power represented by the corresponding element in the second list).
Since all of these function differ only by an operator, I was wondering - is it possible to set a variable to an operator? For example, can you do (something similar to):
var = +
var2 = 5 var 7 #var2 is now 12
I know that specifically doesn't work, but is there anything similar that does work similarly?
Решение 2
Try following:
>>> op = lambda a, b: a + b
>>> result = op(5, 7)
>>> result
12
Другие советы
Yes! You want the operator
module, which "exposes Python's intrinsic operators as efficient functions."
import operator
op = operator.add
var = op(5, 7)
As @falsetru points out, a lambda is handy too; the functions in operator
are going to be a wee bit faster, though:
from timeit import timeit
print timeit("add(5, 7)", "add = lambda x, y: x+y") # about 0.176 OMM
print timeit("add(5, 7)", "from operator import add") # about 0.136 OMM