如何在不舍入的情况下获取小数值

2024-06-15 20:56:30 发布

您现在位置:Python中文网/ 问答频道 /正文

如何在最终答案中添加两个数字并保留其小数位?下面是执行此操作的代码,但它不起作用

import re
cnt=0
s=0
l1= []
with open('C://Users/S/Documents/ok5.txt') as f:
    for i in f:
        if i.startswith('X-DSPAM-Confidence:'):
            x = re.findall('\d*?\.\d+',i)
            l1.append(x)
            cnt+=1

for i in range(0,len(l1)):
    j = float(i)
    s += j

print(l1)    
print(s)

我得到的结果是:

[['0.5454'], ['0.5677']]
1.0

但是,当我尝试下面的简单代码时,它给出了正确的答案:

a = 0.5454
b = 0.5677
c = float(a+b)
print(c)

其输出为:

1.1131

1条回答
网友
1楼 · 发布于 2024-06-15 20:56:30

我想你应该这样做:

import re
cnt=0
s=0
l1= []
with open('C://Users/S/Documents/ok5.txt') as f:
    for i in f:
        if i.startswith('X-DSPAM-Confidence:'):
            x = re.findall('\d*?\.\d+',i)
            l1.append(x)
            s += float(x[0]) # You could just add it here, which improves time complexity
            cnt+=1
print(l1)    
print(s)

相关问题 更多 >