Python计数行数小于或大于

RHK*_*-S8 3 python

我是python的新手并编写一个程序来计算行数.该文件如下所示:

  0.86149806
  1.8628227
 -0.1380086
 -1
  0.99927421
 -1.0007207
  0.99927421
  0.99926955
  -1.0007258
Run Code Online (Sandbox Code Playgroud)

我的代码尝试如下:

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
Run Code Online (Sandbox Code Playgroud)

我试图让它计算低于-0.3的counterNeg所有行,所有高于0.3的行counterPos,以及所有具有介于0.29和-0.29之间的数字的行counterNeu.

它似乎不起作用,我知道我出错for i in line但不确定如何.

kir*_*gin 6

你line是一个字符串,但你想把它解析为float.只是用float(line).

为了以防万一,最好从行的开头和结尾删除所有空格.所以:

for line in infile:
    i = float(line.strip())
    # ... count
Run Code Online (Sandbox Code Playgroud)