简体   繁体   English

在Python 3.7中计算列表

[英]Calculate lists in Python 3.7

I was wondering if it was possible to calculate a list, for example this one 我想知道是否可以计算一个列表,例如这个列表

calculation = [1, "+", 2, "*", 15]

so it returns 31. 因此它返回31。

Don't use eval ever. 永远不要使用eval Check this post 检查这篇文章

Instead you can refer some other library like asteval 相反,您可以引用其他库,例如asteval

from asteval import Interpreter
aeval = Interpreter()
calculation = [1, "+", 2, "*", 15]
aeval.eval(''.join(map(str, calculation)))

Maybe you could take a look at a binary expression tree. 也许您可以看一下二进制表达式树。

binary expression tree 二元表达树

Sure: 当然:

eval(' '.join(map(str, calculation)), {}, {})

The inner join (no pun intended) builds a single string which is valid Python code, then you simply eval() it. 内部join (无双关语)将构建一个有效的Python代码的单个字符串,然后您只需对其进行eval()

The two {} s are optional, they make it so the code runs without access to the surrounding global and local variables. 这两个{}是可选的,它们使之成为可能,因此代码在运行时无需访问周围的全局变量和局部变量。

eval can be used for evaluating an expression (which is in the form of a string) in python. eval可用于在python中评估表达式(以字符串形式)。

Desired output can be obtained as below 所需的输出可通过以下方式获得

eval(''.join([str(x) for x in calculation]))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM