Alternative to eval in Python

前端 未结 2 1736
有刺的猬
有刺的猬 2021-01-13 12:21

Python eval is quite slow. I need to evaluate simple boolean expression with logical operators (like \"True or False\"). I am doing this for thousands of line o

相关标签:
2条回答
  • 2021-01-13 12:47

    It's not clear to me how @CatPlusPlus's solution will evaluate any boolean expression. Here is an example from the pyparsing wiki examples page of a Boolean expression parser/evaluator. Here are the test cases for this script:

    p = True
    q = False
    r = True
    test = ["p and not q",
            "not not p",
            "not(p and q)",
            "q or not p and r",
            "q or not (p and r)",
            "p or q or r",
            "p or q or r and False",
            ]
    
    for t in test:
        res = boolExpr.parseString(t)[0]
        print t,'\n', res, '=', bool(res),'\n'
    
    0 讨论(0)
  • 2021-01-13 12:56
    import operator
    ops = { 'or': operator.or_, 'and': operator.and_ }
    print ops[op](True, False)
    
    0 讨论(0)
提交回复
热议问题