【hackerrank】-Day 11: 2D Arrays----之表格打印

二维数组的表格格式化打印。
比如:给定表格(即list中的每一个list元素的个数相同,不然没法打印了,如下共3个list,每个list都有4个字符串):
tableData = [
[‘apple’, ‘oranges’, ‘cherries’, ‘banana’],
[‘Alice’, ‘Bob’, ‘Carol’, ‘David’],
[‘dogs’, ‘cats’, ‘moose’, ‘goose’]
]
希望可以格式化输出为右对齐如下:

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

思路就是:
1、首先得拿到list中每个子list中的字符串的最大值,即右对齐方法rjust(最大值)需要的参数
2、然后遍历二维数组进行打印,每打印3个col字符串后回车(注意不能是换行),这样最后每一列都是右对齐的子list即最终效果

#! /usr/bin/python3

def printTable(data_list):
    # 定义1个list用来存储每个子list的最长字符串的长度
    str_maxlen_list = [0]*len(data_list)
    # 遍历二维数组,拿到每个子list的最长字符串的长度并存到str_maxlen_list中
    for i in range(len(data_list)):
        for j in range(len(data_list[i])):
            if len(data_list[i][j]) >= str_maxlen_list[i]:
                str_maxlen_list[i] = len(data_list[i][j])
    # 再次遍历二维数组(先遍历内list,再遍历外list--因为最后打印需要每一列都是右对齐的内list)
    for i in range(len(data_list[0])):
        for j in range(len(data_list)):
            # 注意打印时,每打印3个col字符串才换行(3个col字符串用空格或制表符连接起来并打印即可)
            print(data_list[j][i].rjust(str_maxlen_list[j]) + ' ', end='')
        # 回车\r操作,如果此处写换行\n,可能效果不是太好!
        print('\r')

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

printTable(tableData)

效果就是右对齐,如下:

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

猜你喜欢

转载自blog.csdn.net/langhailove_2008/article/details/81837997
今日推荐