Python中eval的替代方法 [英] Alternative to eval in Python
本文介绍了Python中eval的替代方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Python eval
相当慢.我需要使用逻辑运算符(例如"True或False")评估简单的布尔表达式.我正在对数千行数据进行此操作,并且eval
在性能方面是一个巨大的瓶颈.真的很慢.还有其他方法吗?
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?
我尝试创建可能的表达式组合及其预期输出的dict
,但这确实很丑!!
I tried creating a dict
of possible expression combinations and their expected output, but this is really ugly!
此刻我有以下代码:
eval('%s %s %s' % (True, operator, False))
推荐答案
import operator
ops = { 'or': operator.or_, 'and': operator.and_ }
print ops[op](True, False)
这篇关于Python中eval的替代方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文