当前位置: 移动技术网 > IT编程>脚本编程>Python > 【小练习】表格打印 printTable()

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

2020年07月15日  | 移动技术网IT编程  | 我要评论
【小练习】表格打印 printTable()编写一个名为printTable() 的函数,它接受字符串的列表的列表,将它显示在组织良好的表格中,每列右对齐。假定所有内层列表都包含同样数目的字符串。例如,该值可能看起来像这样:tableData = [['apples', 'oranges', 'cherries', 'banana'], ['Alice', 'Bob', 'Carol', 'David'], ['dogs', 'cats', 'moos

【小练习】表格打印 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 

本文地址:https://blog.csdn.net/Kev_Zhang/article/details/107319228

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网