2017-02-11 133 views
1

我有一個任務,我們必須閱讀我們創建的具有測試名稱和分數的文件,並將它們打印在列中。獲取數據並將其與平均值一起顯示並不成問題,但我不明白如何將輸出列中的分數對齊到右側。在輸出示例中,分數與「SCORES」列的權限完全對齊。我可以使用格式(分數,'10d')作爲示例來格式化它們的寬度,但這總是與測試名稱的長度有關。有什麼建議?如何在python中完美對齊兩列?

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()