评估字典变量的数学表达式 [英] Evaluating math expression on dictionary variables
问题描述
我正在做一些工作,评估已保存为JSON对象的日志数据到文件中. 为了方便我的工作,我创建了2个小型python脚本,它们根据正则表达式过滤掉记录的条目,并从事件中打印出多个字段.
I'm doing some work evaluating log data that has been saved as JSON objects to a file. To facilitate my work I have created 2 small python scripts that filter out logged entries according to regular expressions and print out multiple fields from an event.
现在,我希望能够在打印字段时评估简单的数学运算.这样我就可以说
Now I'd like to be able to evaluate simple mathematical operations when printing fields. This way I could just say something like
./print.py type download/upload
,它将打印类型和上传/下载比率.我的问题是我不能使用eval()
,因为这些值实际上在dict
内部.
and it would print the type and the upload to download ratio. My problem is that I can't use eval()
because the values are actually inside a dict
.
有一个简单的解决方案吗?
Is there a simple solution?
推荐答案
eval
可以选择使用globals
和locals
字典.因此,您可以执行以下操作:
eval
optionally takes a globals
and locals
dictionaries. You can therefore do this:
namespace = dict(foo=5, bar=6)
print eval('foo*bar', namespace)
请记住,eval
是邪恶的",因为如果执行的字符串不能被信任,这是不安全的.不过,这对于您的辅助脚本应该没问题.
Keep in mind that eval
is "evil" because it's not safe if the executed string cannot be trusted. It should be fine for your helper script though.
为完善起见,还有ast.literal_eval()
较为安全,但它仅计算文字,这意味着无法给它一个格.
For completness, there's also ast.literal_eval()
which is safer but it evaluates literals only which means there's no way to give it a dict.
这篇关于评估字典变量的数学表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!