如何从Python中的“operator”模块获取数学运算符字符串

发布于 2024-11-14 22:32:31 字数 1053 浏览 0 评论 0原文

operator.add 为例:

>>>import operator as op
>>>op.add(1,2)       #means 1 + 2
3
>>>op.add.__name__
'add'

我想要这样的:

>>>op.add.math_str
"+"

我可以得到所有这些数学字符串 "+", "-", ">"... module < code>operator 支持运行时吗?

编辑:

>>> [eval(x) for x in [".".join(("op",x,"__doc__")) for x in dir(op)]]
['abs(a) -- Same as abs(a).',
 'add(a, b) -- Same as a + b.',
 'and_(a, b) -- Same as a & b.',
 'concat(a, b) -- Same as a + b, for a and b sequences.',
 'contains(a, b) -- Same as b in a (note reversed operands).',
 'delitem(a, b) -- Same as del a[b].',
 'delslice(a, b, c) -- Same as del a[b:c].',
 'div(a, b) -- Same as a / b when __future__.division is not in effect.',
 'str(object) -> string\n\nReturn a nice string representation of the object.\nIf the argument is a string, the return value is the same object.',

上面的代码可以列出大多数运算符字符串,这是否意味着我可以使用 re 模块列出字符串?

谢谢!

Take operator.add for example:

>>>import operator as op
>>>op.add(1,2)       #means 1 + 2
3
>>>op.add.__name__
'add'

I want sort of:

>>>op.add.math_str
"+"

Can I get all those math string "+", "-", ">"... module operator supported runtime?

EDIT:

>>> [eval(x) for x in [".".join(("op",x,"__doc__")) for x in dir(op)]]
['abs(a) -- Same as abs(a).',
 'add(a, b) -- Same as a + b.',
 'and_(a, b) -- Same as a & b.',
 'concat(a, b) -- Same as a + b, for a and b sequences.',
 'contains(a, b) -- Same as b in a (note reversed operands).',
 'delitem(a, b) -- Same as del a[b].',
 'delslice(a, b, c) -- Same as del a[b:c].',
 'div(a, b) -- Same as a / b when __future__.division is not in effect.',
 'str(object) -> string\n\nReturn a nice string representation of the object.\nIf the argument is a string, the return value is the same object.',

above code can list most operators strings, is that means I can list strings with re module?

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

甜扑 2024-11-21 22:32:31

您可以使用教程中的下表 只需构建一次您自己的映射字典,然后在需要时即可使用它。

You can use the following table from tutorial to build your own mappings dictionary only once and then simply use it whenever you will need it.

泪之魂 2024-11-21 22:32:31

不,建立你自己的字典。

No. Build your own dictionary.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文