【发布时间】:2021-02-02 12:09:16
【问题描述】:
我正在尝试在 python 中编写一个函数,它读取文件,提取文件中冒号后的数字,并返回数字的平均值
(平均值的简单公式 => 数字的总和 / 数字的数量)
文件看起来像:
数字1:7
#more 可以添加
thenumber2: 4(#yes冒号后有空格)
应忽略以“#”开头的行。
到目前为止我的代码:
import os
def get_average_n(path):
s = ""
t = 0
v = 0
if not os.path.exists(path):
return None
if os.stat(path).st_size == 0:
return 0.0
else:
p = open(path, "r")
content = p.readlines()
for line in content:
if line.startswith("#"):
continue
elif not line.startswith("#"):
x = line.find(":")
s += line[x + 1:]
h = s.replace("\n", "")
for c in h:
if c.isdigit():
t += float(c)
v += 1
avg = round(t / v, 2)
return avg
print(get_average_n("file.txt"))
在 casementionet (fat) 中输出应该是 5.5 但我得到错误的输出,我真的找不到问题。它返回 6.25 而不是 5.5。
【问题讨论】:
-
不缩进
for c in h:。它应该与elif...对齐 -
仍然得到相同的输出,
-
无关:为什么要检查
if line.startswith('#'),然后检查elif not line.startswith('#')?如果超出if,您知道line不以#开头 -
谢谢,我没有意识到这一点。现在它工作正常,除非数字是浮点数,thenumber1: 3.25 #comment thenumbe2r:5 -> 给我 3.75 但应该是 4.125
标签: python-3.x function file