使用列表中的两个数字在Python中进行简单计算



我刚开始学习Python编程,在我看完travtravy的速成班视频后,我开始做一些小程序来改进它,但是我遇到了一个问题。

假设你让用户输入一个简单的数学计算,它看起来像这样,在这种情况下你想做加法:

x = ['1','+','2','-','3']

然后我想做一个for循环,扫描+并在+符号之前和之后添加数字。但是当它输出预期的结果时,它只是输出整个列表。

for i in x:
if i == "+":
add_sum = float(calc_List[i-1]) + float(calc_List[i+1])
print(add_sum)

当我运行它时,我在终端上得到这个消息:

add_sum = float(x[i-1]) + float(x[i+1])
~^~
TypeError: unsupported operand type(s) for -: 'str' and 'int'

似乎我不能这样写,但是我怎么能从列表中选择i的前一个和下一个数字,然后做任何计算?

我试图保持i计数成一个单独的变量,像这样:

position = 0
for i in x:
position += 1
if i == '+':
a = position - 1
b = position + 1
add_sum = float(x[a]) + float(x[b])

但是我得到的是这个错误:

add_sum = float(x[a]) + float(x[b])
^^^^^^^^^^^
ValueError: could not convert string to float: '+'

您需要在x中找到i的索引,然后在列表中找到前后值。这可以这样实现:

x = ['1', '+', '2', '-', '3']
for i in x:
if i == "+":
add_sum = float(x[x.index(i)-1]) + float(x[x.index(i)+1])
print(add_sum)

这个输出:

3.0

希望对你有帮助。

using eval()

代码:

x = ['1','+','2','-','3']
y="".join(x)
print(eval(y))  

输出: -

0

第二个方法:-这将在您的情况下工作…!

代码:

x = ['1','+','2','-','3']
check=0
for i in x:
if i=="+" or i=="-":
check+=1
for i in range(len(x)+check-1): #Assuming The sign (+,-) where present has previous and forward numbers 
if x[i]=="+":
temp1=int(x[i-1])+int(x[i+1])
x.insert(i+2,str(temp1))
if x[i]=="-":
temp2=int(x[i-1])-int(x[i+1])
x.insert(i+2,str(temp2))
#print(x)   #values how store in the list
print(x[-1])

输出: -

0

最新更新