如何从Python中的“operator”模块获取数学运算符字符串
以 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用教程中的下表 只需构建一次您自己的映射字典,然后在需要时即可使用它。
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.
不,建立你自己的字典。
No. Build your own dictionary.