需要在一个python列表中进行计算

Need to perform calculation in a python list

我在 python 中有一个列表,例如 [1, '+', 32, '+', 56, '+', 34]。 我正在尝试进行数学运算并得到最终结果 123.

我已经接受了用户的输入并完成了数值的 int 转换并创建了这个列表,现在我想给出最终结果。

我需要一些关于如何进行的想法。

如有帮助将不胜感激

快捷方式:

eval(' '.join(str(x) for x in  [1, '+', 32, '+', 56, '+', 34]))

我发现 eval 是一种丑陋的解决方案;我建议以这种方式处理它:

from operator import add, sub

def process(instructions):
    result = 0
    operations = {'+': add, '-': sub}
    operation = add 
    for item in instructions:
        if item in operations:
            operation = operations[item]
        else:
            number = float(item)
            result = operation(result, number)
    return result

your_instructions = [1, '+', 32, '+', 56, '+', 34]
process(your_instructions)
a=[1, '+', 32, '+', 56, '+', 34]
sum([elem for elem in a if elem!='+'])

如何去掉加号并使用sum