用Python自动化枯燥的东西,第6章实践项目

2024-09-29 03:40:24 发布

您现在位置:Python中文网/ 问答频道 /正文

关于“用Python自动化无聊的东西”一书中第6章实践项目的解决方案,我有一个简短的问题。我应该编写一个函数,以列表的形式获取数据:

tableData = [['apples', 'oranges', 'cherries', 'banana'],
             ['Alice', 'Bob', 'Carol', 'David'],
             ['dogs', 'cats', 'moose', 'goose']]

并打印下表,每列右对齐:

  apples Alice  dogs
 oranges   Bob  cats
cherries Carol moose
  banana David goose

问题是,我的代码:

def printTable(table):
    colsWidths = [0]*len(table) #this variable will be used to store width of each column
    # I am using max function with key=len on each list in the table to find the longest string --> it's length be the length of the colum
    for i in range(len(table)):
        colsWidths[i] = len(max(table[i], key = len)) # colsWidths = [8,5,5]
    # Looping through the table to print columns
    for i in range(len(table[0])):
        for j in range(len(table)):
            print(table[j][i].rjust(colsWidths[j], " "), end = " ")
        print("\n")

打印每行之间有过多空行的表格:

printTable(tableData)

  apples Alice  dogs

 oranges   Bob  cats

cherries Carol moose

  banana David goose

我知道它与程序末尾编写的print语句有关,但没有它,所有内容都会打印出来。所以我的问题是,有没有办法从表中删除这些空行


Tags: theinlentablebananabobdavidprint
1条回答
网友
1楼 · 发布于 2024-09-29 03:40:24

print("\n")替换为print()

print默认情况下打印一个换行符,这就是end参数的默认值

当您执行print("\n")时,实际上是在打印两行新行

相关问题 更多 >