Alternative to eval in Python

纵饮孤独 提交于 2019-12-01 05:25:39

问题


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 of data and eval is a huge bottleneck in terms of performance. It's really slow.. Any alternative approaches?

I tried creating a dict of possible expression combinations and their expected output, but this is really ugly!

I have the following code at the moment:

eval('%s %s %s' % (True, operator, False))

回答1:


import operator
ops = { 'or': operator.or_, 'and': operator.and_ }
print ops[op](True, False)



回答2:


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'


来源:https://stackoverflow.com/questions/7882987/alternative-to-eval-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!