python 表格打印代码实例解析

yipeiwu_com6年前Python基础

编写一个名为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设计】。

相关文章

python接口自动化如何封装获取常量的类

这篇文章主要介绍了python接口自动化如何封装获取常量的类,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 背景: 一、执行case的...

我就是这样学习Python中的列表

1. 列表 对于python列表的理解可以和C语言里面的数组进行比较性的记忆与对照,它们比较相似,对于python里面列表的定义可以直接用方括号里加所包含对象的方法,并且python的...

python安装PIL模块时Unable to find vcvarsall.bat错误的解决方法

可能很多人遇到过这个错误,当使用setup.py安装python2.7图像处理模块PIL时,python默认会寻找电脑上以安装的vs2008.如果你没有安装vs2008,会出现Unabl...

21行Python代码实现拼写检查器

引入 大家在使用谷歌或者百度搜索时,输入搜索内容时,谷歌总是能提供非常好的拼写检查,比如你输入 speling,谷歌会马上返回 spelling。 下面是用21行python代码实现的一...

python中的数据结构比较

列表:list=[val1,val2] 1.列表中的每一个元素都是可变的,有序的,可以被查看索引的。 可变意味着可以对每个元素进行增删改查的操作,列表中的元素可以是Python中的任...