1
テスト名とスコアを持つファイルを読み込んで列に印刷するという課題があります。平均と一緒にデータを取得して表示することは問題ありませんが、出力列のスコアをどのように調整するのか分かりません。出力例では、得点は「得点」列の右に完全に並んでいます。私はフォーマット(スコア、 '10d')を例にしてその幅をフォーマットすることができますが、それはいつもテストの名前の長さに相対的です。何かアドバイス?Pythonで2つの列を完全に揃える方法は?
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()
すべての行のリストを取得します。最長の「得点」を見つける。列の幅を計算し、その形式で使用します。 – DyZ
[tabulate](https://pypi.python.org/pypi/tabulate)や[terminaltables](https://pypi.python.org/pypi/terminaltables)のようなライブラリが役立つかもしれません。これらのようなものがたくさんあります。 –
あなたはtests.txtの例を提供できます – ands