Python 摆桌子
我必须编写一个程序,导入一个文本文件,计算测试平均值,然后将其打印到表格中。除了表格的格式之外,我已经能够让所有的东西都工作了 这是桌子的外观 阅读六个测试和分数Python 摆桌子,python,python-3.x,Python,Python 3.x,我必须编写一个程序,导入一个文本文件,计算测试平均值,然后将其打印到表格中。除了表格的格式之外,我已经能够让所有的东西都工作了 这是桌子的外观 阅读六个测试和分数 TEST---------------SCORE objects------------88 loops--------------95 selections---------86 variables
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()
按选项卡分隔列可能是个坏主意,因为很难预测需要多少选项卡。您可以改为使用打印格式,例如:
print('{:20} {}'.format(name, score))
这将打印name
填充到20个字符,然后score
。我假设表中的-
只是空格字符。如果您想了解更多,您可以阅读一次文件,然后在saymax\u name\u length
中找到最长的name
,然后执行以下操作:
print('{:{}} {}'.format(name, max_name_length, score))
请参阅有关格式规范字符串的完整详细信息。按制表符分隔列可能不是一个好主意,因为很难预测需要多少制表符。您可以改为使用打印格式,例如:
print('{:20} {}'.format(name, score))
这将打印name
填充到20个字符,然后score
。我假设表中的-
只是空格字符。如果您想了解更多,您可以阅读一次文件,然后在saymax\u name\u length
中找到最长的name
,然后执行以下操作:
print('{:{}} {}'.format(name, max_name_length, score))
请参阅有关格式规范字符串的完整详细信息。您可以使用'{:-您可以使用'{:-可能重复的