问题描述
我必须编写一个程序来导入文本文件,计算出测试平均值,然后将其打印到表格中。 除了表格的格式,我已经能够使所有工作正常进行。
这是桌子的外观
阅读六项测试和分数
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楼
 
     您可以使用'{:-<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}的字典。 
     zip(f, f)是一个小技巧,因为test和score在不同的行上,所以一次只能在文件的两行中浏览。 
2楼
用选项卡分隔列可能不是一个好主意,因为很难预测将需要多少个选项卡。 您可以改用打印格式,例如:
print('{:20} {}'.format(name, score))
 
   
     此打印name填充到20个字符,然后score 。 
     我假设-在您的表格中只是空格字符。 
     如果想花哨的话,可以阅读一次文件,然后在max_name_length找到最长的name ,然后执行以下操作: 
print('{:{}} {}'.format(name, max_name_length, score))
 
  请参阅有关格式规范字符串的完整详细信息。