如何在python中完美地对齐两列?

时间:2017-02-11 18:59:52

标签: python alignment multiple-columns

我有一项任务,我们必须阅读我们创建的具有测试名称和分数的文件并将其打印在列中。获取数据并显示数据以及平均值是没有问题的,但我不明白如何在输出列中将分数对齐到右边。在输出示例中,分数完全排列在“SCORES”列的右侧。我可以使用格式(分数,'10d')格式化它们的宽度作为示例,但这总是相对于测试名称的长度。有什么建议?

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

1 个答案:

答案 0 :(得分:0)

您只需将每个名称和分数存储在一个列表中,然后计算最长的名称,并使用此长度为较短的名称打印空格。

def main():
    with open('tests.txt', 'r') as f:
        data = []
        totalTestscoresVaule = 0
        numberOfexams = 0

        while True:
            exam_name = f.readline().rstrip('\n')

            if exam_name == "":
                break

            line = f.readline().rstrip('\n')
            test_score = float(line)
            totalTestscoresVaule += test_score

            data.append({'name': exam_name, 'score': test_score})

            numberOfexams += 1
            averageOftheTestscores = totalTestscoresVaule / numberOfexams

        longuest_test_name = max([len(d['name']) for d in data])

        print("Reading  tests and scores")
        print("============================")
        print("TEST{0} SCORES".format(' ' * (longuest_test_name - 4)))

        for d in data:
            print(format(d['name']), end=" ")
            print(format(" " * (longuest_test_name - len(d['name']))), end="")
            print(repr(d['score']).ljust(20))

        print("Average is", (averageOftheTestscores))


main()