3

私は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

counterNeg-0.3 未満のすべての行を 、0.3 を超えるcounterPosすべての行を 、および 0.29 から -0.29 までの数値を持つすべての行をカウントするようにしようとしていcounterNeuます。

うまくいかないようですが、うまくいかないことはわかっていますが、どうすればよいfor i in lineかわかりません。

4

3 に答える 3

6

あなたlineは文字列ですが、それをfloat. を使用するだけfloat(line)です。

念のため、行の最初と最後からすべての空白を削除することもお勧めします。そう:

for line in infile:
    i = float(line.strip())
    # ... count
于 2013-06-05T18:43:34.777 に答える
-1

多くのテストを行っていることに気付いたときは、通常、次のようなことを行います。

data='''\
  0.86149806
  1.8628227
 -0.1380086
 -1
  0.99927421
 -1.0007207
  0.99927421
  0.99926955
  -1.0007258'''

def f1(x):
    ''' >0.3 '''
    return x>0.3

def f2(x):
    ''' <-0.3 '''   
    return x<-.3

def f3(x):
    ''' not f1 and not f2 '''   
    return not f1(x) and not f2(x)

tests={f1: 0,
       f2: 0,
       f3: 0 }

for line in data.splitlines():
    for test in tests:
        if test(float(line.strip())): 
            tests[test]+=1

for f,v in sorted(tests.items()):
    print '{:3}{:20}:{}'.format(f.__name__, f.__doc__, v)

版画:

f1  >0.3               :5
f2  <-0.3              :3
f3  not f1 and not f2  :1
于 2013-06-05T20:10:31.327 に答える