Python中eval的替代方法

编程入门 行业动态 更新时间:2024-10-26 17:19:08
本文介绍了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的替代方法

本文发布于:2023-11-15 17:29:03,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1596501.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:方法   Python   eval

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!