首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用Python自动编写无聊的东西,第6章实践项目

用Python自动编写无聊的东西,第6章实践项目
EN

Stack Overflow用户
提问于 2020-05-04 10:27:30
回答 1查看 459关注 0票数 0

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

代码语言:javascript
复制
tableData = [['apples', 'oranges', 'cherries', 'banana'],
             ['Alice', 'Bob', 'Carol', 'David'],
             ['dogs', 'cats', 'moose', 'goose']]

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

代码语言:javascript
复制
  apples Alice  dogs
 oranges   Bob  cats
cherries Carol moose
  banana David goose

问题是,我的代码:

代码语言:javascript
复制
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")

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

代码语言:javascript
复制
printTable(tableData)

  apples Alice  dogs

 oranges   Bob  cats

cherries Carol moose

  banana David goose

我知道这与在程序结束时编写的print语句有关,但是没有它,所有的东西都会被打印出来。所以我的问题是,有没有办法从表中删除那些空行?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-05-04 10:29:25

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

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

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

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61590070

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档