我是 python 的新手,正在编写一个程序来计算行数。该文件如下所示:
0.86149806
1.8628227
-0.1380086
-1
0.99927421
-1.0007207
0.99927421
0.99926955
-1.0007258
我的代码尝试如下:
counterPos = 0
counterNeg = 0
counterTot = 0
counterNeu = 0
with open('test.txt', 'r') as infile:
for line in infile:
counterTot += 1
for i in line:
if i > 0.3:
counterPos += 1
elif i < -0.3:
counterNeg += 1
else:
counterNeu += 1
我试图让它将所有低于 -0.3 的行计数为 counterNeg
,将所有高于 0.3 的行计数为 counterPos
,以及所有介于两者之间的数字的行0.29 和 -0.29 到 counterNeu
。
虽然它似乎不起作用,我知道我在 for i in line
上出错了,但不确定如何。
最佳答案
您的行
是一个字符串,但您想将其解析为 float
。只需使用 float(line)
。
为了以防万一,最好去掉行首和行尾的所有空格。所以:
for line in infile:
i = float(line.strip())
# ... count
关于Python 计算数字小于或大于的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16947457/