形成一张桌子

时间:2017-02-16 01:31:34

标签: python python-3.x

我必须编写一个导入文本文件的程序,计算测试平均值然后将其打印到表中。除了表的格式之外,我已经能够完成所有工作。

以下是表格的外观

阅读六项考试和分数

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

2 个答案:

答案 0 :(得分:2)

您可以使用'{:-<20}{}'.format(test, score)左对齐并使用&#39; - &#39;来填充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是一次逐步浏览文件的小技巧。

答案 1 :(得分:0)

按标签分隔列可能不是一个好主意,因为很难预测需要多少个标签。您可以使用打印格式,例如:

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

这会将name打印为20个字符,然后score。我假设你的表中的-只是间隔字符。如果您想获得想象力,可以阅读该文件一次并找到name中最长的max_name_length,然后执行:

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

查看有关格式规范字符串in the official documentation的完整详细信息。

相关问题