《Python编程快速上手—让繁琐工作自动化》第6章实践项目答案

6.7 表格打印

编写一个名为printTable()的函数,它接受字符串的列表的列表,将它显示在组织良好的表格中,每列右对齐。假定所有内层列表都包含同样数目的字符串。例如,该值可能看起来像这样:


123.JPG

方法一

def printTable(tableData):
    width = [max(map(len, group)) for group in tableData]
    for x in range(len(tableData[0])):
        for y in range(len(tableData)):
            print(tableData[y][x].rjust(width[y]), end=' ')
        print('')


tableData = [['apple', 'orange', 'cherries', 'banana'],
             ['Alice', 'Bob', 'Carol', 'David'],
             ['dog', 'cats', 'moose', 'goose']]

printTable(tableData)

方法二

def printTable(tableData):
    width = [max(map(len, group)) for group in tableData]
    for group in zip(*tableData):
        for index, item in enumerate(group):
            print(item.rjust(width[index]), end=' ')
        print('')


tableData = [['apple', 'orange', 'cherries', 'banana'],
             ['Alice', 'Bob', 'Carol', 'David'],
             ['dog', 'cats', 'moose', 'goose']]

printTable(tableData)

程序运行结果

   apple Alice   dog 
  orange   Bob  cats 
cherries Carol moose 
  banana David goose 

Process finished with exit code 0
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容