繁体   English   中英

使用 Python 自动化无聊的东西,第 6 章练习项目

[英]Automate Boring Stuff with Python, Chapter 6 Practice Project

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

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 语句有关,但没有它,一切都会被打印出来。 所以我的问题是,有没有办法从表中删除那些空行?

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM