Python - 有没有办法将操作(+ - */)存储在列表中或作为变量?

标签 python python-3.x

<分区>

我问的原因纯粹是出于好奇。我可以看到,如果您事先不知道要对某些变量应用什么操作,或者在递归调用的某个级别应用不同的操作,或者它可能只是使某些事情更容易和/或更整洁。

虽然我只是猜测,这可能是一个非常糟糕的主意,但总的来说我只是好奇。

最佳答案

您可以使用 operator模块。

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 expression x+y. The function names are those used for special class methods; variants without leading and trailing __ are also provided for convenience.

所以在列表中存储“操作”很简单:

import operator
operations = [operator.add, operator.sub]
# add two numbers
s = operations[0](1, 2)

关于Python - 有没有办法将操作(+ - */)存储在列表中或作为变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37142837/

相关文章:

python - 对象 (ctx: )>"上的 ValueError : Invalid field u'field' in leaf "<osv.ExtendedLeaf: (u' field', u'in', [59]) - Odoo v8

Python 返回语法错误

python3.4 安装 Flask 给出与 Jinja2 要求相关的错误消息

python - 使用 BeautifulSoup 在 Python 中循环 Href

python - 如何在 Python 3.x 中过滤掉包含无效字符的列表元素?

python - 在 Python 中测试 flash 消息的内容

Python - 检查当前是否正在处理异常

python - 如何在一个 django 模板页面中显示多个 matplotlib 图

python - 编辑 QTableView 单元格后如何更改背景颜色?

python - 位置权限弹出窗口