无法计算替换某些符号的两个值

Can't calculate two values replacing certain sign

如何添加两个值来替换它们之间的 /?我尝试使用 item.replace("/","+") 但它只放置 + 符号替换 / 并且什么都不做。例如,如果我在 2/1.5-3/-4.5 上尝试逻辑,我会得到 2+1.5-3+-4.5

My intention here is to add the two values replacing / between them and divide it into 2 so that the result becomes 1.875 and -3.75 respectively if I try the logic on (2/1.5 and -3/-4.5).

这是我目前的尝试:

for item in ['2/1.5','-3/-4.5']:
    print(item.replace("/","+"))

我现在拥有的:

2+1.5
-3+-4.5

预期输出(将 / 替换为 + 的两个值相加,然后将结果除以二):

1.75
-3.75
from ast import literal_eval

l = ['2/1.5','-3/-4.5']
print([literal_eval(i.replace('/','+'))/2 for i in l])

您可以像这样使用 eval 来完成:

for item in ['2/1.5','-3/-4.5']:
    print((eval(item.replace("/","+")))/2)

你可以这样做(将字符串分成两个浮点数):

for item in ['2/1.5','-3/-4.5']:
    itemArray = item.split("/")
    itemResult = float(itemArray[0]) + float(itemArray[1])
    print(itemResult/2)

由于/只是一个分隔符,其实不需要用+来代替,而是用split来代替,然后总结一下各部分:

for item in ['2/1.5', '-3/-4.5']:
    result = sum(map(float, item.split('/'))) / 2
    print(result)

或更一般化的形式:

from statistics import mean

for item in ['2/1.5', '-3/-4.5']:
    result = mean(map(float, item.split('/')))
    print(result)

我的回答和其他人没什么不同,除了我不明白为什么每个人都在使用列表。这里不需要列表,因为它不会被更改,tuple 很好并且更有效:

for item in '2/1.5','-3/-4.5':            # Don't need a list here
    num1, num2 = item.split('/')
    print((float(num1) + float(num2)) / 2)

@daniel 回答的进一步阐述:

[sum(map(float, item.split('/'))) / 2 for item in ('2/1.5','-3/-4.5')]

结果:

[1.75, -3.75]