python实例5-表格打印

Posted WLinux的随笔

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python实例5-表格打印相关的知识,希望对你有一定的参考价值。

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

table_data = [[‘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  

示例代码1:

import copy


def count_width(the_list):
    new_list = copy.deepcopy(the_list)
    col_widths = [0]*len(the_list)
    i = 0
    while i < len(new_list):
        new_list[i].sort(key=lambda x: len(x), reverse=True)
        col_widths[i] = new_list[i][0]
        i = i+1
    return col_widths


def list_ljust(the_list):
    widths = count_width(the_list)
    for j in range(len(the_list[0])):
        for i in range(len(the_list)):
            print(the_list[i][j].ljust(len(widths[i])), end=‘ ‘)
        print(‘
‘)


table_data = [[‘apples‘, ‘oranges‘, ‘cherries‘, ‘banana‘],
              [‘Alice‘, ‘Bob‘, ‘Carol‘, ‘David‘],
              [‘dogs‘, ‘cats‘, ‘moose‘, ‘goose‘]]
list_ljust(table_data)  

sort方法:

lambda函数:

示例代码2:

def count_widths(the_list):
    col_widths = [0]*len(the_list)
    for i in range(len(the_list)):
        for j in range(len(the_list[0])):
            if len(the_list[i][j]) > max_len:
                max_len = len(the_list[i][j])
        col_widths[i] = max_len
    return col_widths


def list_ljust(the_list):
    widths = count_widths(the_list)
    print(widths)
    for j in range(len(the_list[0])):
        for i in range(len(the_list)):
            print(the_list[i][j].ljust(widths[i]), end=‘ ‘)
        print(‘
‘)


table_data = [[‘apples‘, ‘oranges‘, ‘cherries‘, ‘banana‘],
              [‘Alice‘, ‘Bob‘, ‘Carol‘, ‘David‘],
              [‘dogs‘, ‘cats‘, ‘moose‘, ‘goose‘]]
list_ljust(table_data)

 

以上是关于python实例5-表格打印的主要内容,如果未能解决你的问题,请参考以下文章

逐行打印嵌套列表 - Python

python python中的漂亮(或漂亮打印)JSON对象具有这一功能。在尝试了解什么时,我总是使用这个片段

python常用代码

Python基础

python 实例化形式片段

Python - 如何从打印信息的单独进程中实时读取类实例