[英]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。
Maybe you could take a look at a 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.