项目要求:编写一个名为 printTable()的函数,它接受字符串的列表的列表,将它显示在组织良好的表格中,每列右对齐。

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

打印成以下格式

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

与之前的字符图网格很类似

http://www.jdlhm.com/?p=960

 

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


def printTable():
    max_phy = []
    for items in tableData:
        max_char = len(max(items, key=len))
        max_phy.append(max_char)
    for j in range(len(tableData[0])):
        for i in range(len(tableData)):
            print(tableData[i][j].rjust(max_phy[i]), end=' ')
        print()
printTable()

1. 定义一个空列表,用来tableData列表中,每个子列表里长度最大的那个

2. 假定列表里的小列表为items,以字符串长度(len)为key,求出每个items中最长的字符串长度

3. 将每个最大长度放入到空列表

4. 根据每个items中最大长度进行右对齐,每打印一个字符串结尾加空格

5. 当打印完一行,打印一个换行符

6. 求列表中最长的字符串长度还有一种写法(不知道是不是固定写法,去问一下)

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


def printTable():
    max_phy = []
    for item_out in tableData:
        max_char = max(len(item_in) for item_in in item_out)
        max_phy.append(max_char)
    for j in range(len(tableData[0])):
        for i in range(len(tableData)):
            print(tableData[i][j].rjust(max_phy[i]), end=' ')
        print()
printTable()

 

posted on 2021-08-09 00:24  讲道理好嘛  阅读(57)  评论(0编辑  收藏  举报