码迷,mamicode.com
首页 > 编程语言 > 详细

python实例5-表格打印

时间:2019-10-12 01:29:54      阅读:135      评论:0      收藏:0      [点我收藏+]

标签:字符   idt   end   打印   while   dog   app   apple   epc   

编写一个名为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(‘\r‘)


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(‘\r‘)


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

 

python实例5-表格打印

标签:字符   idt   end   打印   while   dog   app   apple   epc   

原文地址:https://www.cnblogs.com/wlinuxtop/p/11657753.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!