2017-02-16 49 views
0

我必須編寫一個程序來導入文本文件,計算測試平均值,然後將其打印到表格中。除了表格的格式外,我能夠讓所有的東西都能工作。形成表格

下面是表應該如何看

讀6次測試,成績

TEST---------------SCORE                 
objects------------88 
loops--------------95 
selections---------86 
variables----------82 
files--------------100 
functions----------80 

Average is 

我無法弄清楚如何讓物體,循環,選擇等會馬上下對方這裏。但是,桌子應該如何設置。我只是無法將分數排列在分數列中。

這是我的代碼。

def main(): 
    print('Reading six tests and scores') 
    print('TEST\tSCORE') 
    test_scores = open('tests.txt', 'r') 
    total_score = 0 
    counter = 0 
    line = test_scores.readline() 


    while line != '': 
     name = line.rstrip('\n') 
     score = int(test_scores.readline()) 
     total_score += score 
     print(name, score, sep='\t') 
     line = test_scores.readline() 
     counter += 1 

    test_scores.close() 
    average_test = total_score/counter 

    print('Average is', format(average_test, '.1f')) 


main() 
+1

[在Python中表格格式化文本]的可能重複(http://stackoverflow.com/questions/16110230/formatting-text-in-a-table-in-python) –

回答

2

您可以使用'{:-<20}{}'.format(test, score)要左對齊和墊20個字符以「 - 」:

def main(): 
    print('Reading six tests and scores') 
    print('{:-<20}{}'.format('TEST', 'SCORE')) 
    with open('tests.txt') as f: 
     scores = {test.rstrip('\n'): int(score) for test, score in zip(f, f)} 

    for test, score in scores.items(): 
     print('{:-<20}{}'.format(test, score)) 
    print('\nAverage is {:.1f}'.format(sum(scores.values())/len(scores))) 

>>> main() 
Reading six tests and scores 
TEST----------------SCORE 
objects-------------88 
loops---------------95 
functions-----------80 
selections----------86 
variables-----------82 
files---------------100 

Average is 88.5 

注:我搬到使用with聲明,提供的文件的適當處理和構造的字典{test: score}。由於testscore位於不同的行上,所以zip(f, f)是一步一步掃描文件2行的小技巧。

0

按標籤分隔列可能是一個壞主意,因爲很難預測需要多少標籤。您可以使用打印的格式,而不是像這樣,例如:

print('{:20} {}'.format(name, score)) 

這將打印name填充至20個字符,然後score。我假設你的表格中的-只是間隔字符。如果你想獲得幻想,你可以讀取文件一次,並且在說max_name_length找到最長name,然後執行:

print('{:{}} {}'.format(name, max_name_length, score)) 

查看有關格式規範字符串in the official documentation的全部細節。