【问题标题】:How to align two columns perfectly in python?如何在python中完美对齐两列?
【发布时间】:2017-02-11 18:59:51
【问题描述】:

我有一个任务,我们必须读取我们创建的包含测试名称和分数的文件,并将它们打印在列中。获取数据并将其与平均值一起显示是没有问题的,但我不明白如何将分数与输出列中的右侧对齐。在输出示例中,分数在“SCORES”列的右侧完美排列。我可以使用 format(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()

【问题讨论】:

  • 获取所有行的列表;找到最长的“分数”;计算列宽并在格式中使用。
  • 也许像 tabulateterminaltables 这样的库可以帮助你。有很多这样的。
  • 你能提供tests.txt的例子吗
  • @DYZ 这听起来是个好主意!你能举个例子吗?谢谢!

标签: python alignment multiple-columns


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-02
    • 2019-04-24
    • 1970-01-01
    • 2012-10-30
    相关资源
    最近更新 更多