Python - 有没有办法将操作(+ - */)存储在列表中或作为变量? [英] Python - is there a way to store an operation(+ - * /) in a list or as a variable?
问题描述
我问的原因纯粹是好奇.我可以看到,如果您事先不知道要对某些变量应用哪些操作,或者在递归调用的某个级别期间应用不同的操作,这可能很有用,或者可能只是让某些事情变得更简单和/或更整洁.
The reason I ask is pure curiosity. I could see, possibly, that this might be useful if you didn't know ahead of time what operations you wanted to apply to certain variables, or to apply a different operation during a certain level in a recursive call, or perhaps it may just make certain things easier and/or neater.
虽然我只是推测,这可能是一个非常糟糕的主意,但总的来说我只是好奇.
Though am just speculating, it could be a really bad idea, but overall am just curious.
推荐答案
您可以使用 operator
模块.
You may use operator
module.
operator
模块导出一组高效函数对应于 Python 的内在运算符.例如,operator.add(x, y)
等价于表达式 x+y
.功能名称是用于特殊类方法的名称;变体没有为了方便起见,还提供了前导和尾随 __.
The
operator
module exports a set of efficient functions corresponding to the intrinsic operators of Python. For example,operator.add(x, y)
is equivalent to the expressionx+y
. The function names are those used for special class methods; variants without leading and trailing __ are also provided for convenience.
所以在列表中存储操作"就像这样简单:
So storing "operation" in list is as simple as:
import operator
operations = [operator.add, operator.sub]
# add two numbers
s = operations[0](1, 2)
这篇关于Python - 有没有办法将操作(+ - */)存储在列表中或作为变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!