【小练习】表格打印 printTable()

【小练习】表格打印 printTable()

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

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

你的printTable() 函数将打印出:

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

colWidth = [0] * len(table) 创建了一个列表包含最大长度

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

def printTable(table):
    colWidth = [0]*len(table)              # 记录最大长度
    max = 0
    for i in range(len(colWidth)):
        for j in range(len(table[0])): 
            if len(table[i][j]) > colWidth[i]:
                max = len(table[i][j])
            colWidth[i] = max
    for m in range(len(table[0])):
        for n in range(len(table)):
            print(table[n][m].rjust(colWidth[n]), end = ' ')
        print('\n',end = '')

printTable(tableData)

左右对齐均可( ljust / rjust)
左对齐:

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

右对齐:

  apples Alice  dogs 
 oranges   Bob  cats 
cherries Carol moose 
  banana David goose 
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值