编写一个名为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)
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。