编写一个名为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)

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!