我希望使用 python 3.8 中列表中的元素进行计算



我希望制作一个程序,用户在其中输入总和,例如 5 + 6 - 7,我的程序识别它并给出答案,例如 4。到目前为止,我的程序将接受输入,重新识别数字和运算,并将它们分配给一个列表,但是,我不确定如何获取数字和运算符并计算它们。有人有什么可以帮忙的吗?

这是我的代码

s = "5 + 6 - 7" #User input placeholder
q = s.split() #splits the input into a list with an element for every character(not spaces)
print(q)
n = [] #numbers in user input
a = [] #actions/operations that the user inputs
print(q)

for x in range(0, len(q)):
if q[x].isdigit(): #determines whether an element is a digit
q[x] = int(q[x]) #str to int
n.append(q[x]) #adds it to the n list
print(n)
else:
a.append(q[x]) #adds an operation to the a list
print(a)
answer = n[0], a[0], n[1], a[1], n[2]
print("Operations are: ", a)
print("Numbers are: ", n)
print("Answer is: ", answer)

operator模块允许您直接访问 Python 中的所有标准运算符作为函数。

您可以将每个运算符函数分配给其文本表示形式,并使用它来查找运算符:

ops = {'+': operator.add, '-': operator.sub}

运行数字和运算符,从列表中选择每个操作的两个参数并应用它,然后将结果推回列表中:

print("Operations are: ", a)
print("Numbers are: ", n)
for operation in a:
arg_a = n.pop(0)
arg_b = n.pop(0)
result = ops[operation](arg_a, arg_b)
n.insert(0, result)
print("Answer is: ", n[0])

保留在n列表中的元素是请求的计算答案。这假定计算格式正确。

在这种情况下,您可以使用识别表达式并计算输出的eval()

例如

s = "5 + 6 - 7"
print(eval(s))

输出:

4

这是你能做的最简单的事情。希望对您有所帮助!

最新更新