相关疑难解决方法(0)

按符号访问操作员功能

我需要一个函数,它将python的运算符符号或关键字之一作为字符串,连同其操作数,对其进行求值,并返回结果.像这样:

>>> string_op('<=', 3, 3)
True
>>> string_op('|', 3, 5)
7
>>> string_op('and', 3, 5)
True
>>> string_op('+', 5, 7)
12
>>> string_op('-', -4)
4
Run Code Online (Sandbox Code Playgroud)

不能认为该字符串是安全的.我只对映射二元运算符感到满意,但如果能得到所有这些运算符,我会非常高兴.

我当前的实现手动将符号映射到运算符模块中的函数:

import operator

def string_op(op, *args, **kwargs):
    """http://docs.python.org/2/library/operator.html"""
    symbol_name_map = {
        '<': 'lt',
        '<=': 'le',
        '==': 'eq',
        '!=': 'ne',
        '>=': 'ge',
        '>': 'gt',
        'not': 'not_',
        'is': 'is_',
        'is not': 'is_not',
        '+': 'add', # conflict with concat
        '&': 'and_', # (bitwise)
        '/': 'div',
        '//': 'floordiv',
        '~': 'invert',
        '%': 'mod',
        '*': …
Run Code Online (Sandbox Code Playgroud)

python functional-programming idioms

5
推荐指数
1
解决办法
1407
查看次数

标签 统计

functional-programming ×1

idioms ×1

python ×1