2017-02-11 9 views
1

テスト名とスコアを持つファイルを読み込んで列に印刷するという課題があります。平均と一緒にデータを取得して表示することは問題ありませんが、出力列のスコアをどのように調整するのか分かりません。出力例では、得点は「得点」列の右に完全に並んでいます。私はフォーマット(スコア、 '10d')を例にしてその幅をフォーマットすることができますが、それはいつもテストの名前の長さに相対的です。何かアドバイス?Pythonで2つの列を完全に揃える方法は?

def main(): 
     testAndscores = open('tests.txt', 'r') 
     totalTestscoresVaule = 0 
     numberOfexams = 0 
     line = testAndscores.readline() 
     print("Reading tests and scores") 
     print("============================") 
     print("TEST  SCORES") 
     while line != "": 
       examName = line.rstrip('\n') 
       testScore = float(testAndscores.readline()) 
       totalTestscoresVaule += testScore 


       ## here is where I am having problems 
       ## can't seem to find info how to align into 
       ## two columns. 
       print(format(examName),end="")   
       print(format(" "),end="") 
       print(repr(testScore).ljust(20)) 

       line = testAndscores.readline() 
       numberOfexams += 1 
       averageOftheTestscores = totalTestscoresVaule/numberOfexams 
       print("Average is", (averageOftheTestscores)) 

       #close the file 
       testAndscores.close() 

    main() 
+2

すべての行のリストを取得します。最長の「得点」を見つける。列の幅を計算し、その形式で使用します。 – DyZ

+0

[tabulate](https://pypi.python.org/pypi/tabulate)や[terminaltables](https://pypi.python.org/pypi/terminaltables)のようなライブラリが役立つかもしれません。これらのようなものがたくさんあります。 –

+0

あなたはtests.txtの例を提供できます – ands

答えて

0

あなただけのそれぞれの名前を格納し、リストに得点し、最も長い名前を計算し、そして短い名前のためのスペースを印刷するには、この長さを使用する必要があります。

def main(): 
    with open('tests.txt', 'r') as f: 
     data = [] 
     totalTestscoresVaule = 0 
     numberOfexams = 0 

     while True: 
      exam_name = f.readline().rstrip('\n') 

      if exam_name == "": 
       break 

      line = f.readline().rstrip('\n') 
      test_score = float(line) 
      totalTestscoresVaule += test_score 

      data.append({'name': exam_name, 'score': test_score}) 

      numberOfexams += 1 
      averageOftheTestscores = totalTestscoresVaule/numberOfexams 

     longuest_test_name = max([len(d['name']) for d in data]) 

     print("Reading tests and scores") 
     print("============================") 
     print("TEST{0} SCORES".format(' ' * (longuest_test_name - 4))) 

     for d in data: 
      print(format(d['name']), end=" ") 
      print(format(" " * (longuest_test_name - len(d['name']))), end="") 
      print(repr(d['score']).ljust(20)) 

     print("Average is", (averageOftheTestscores)) 


main() 
関連する問題