python 表格打印代码实例解析

yipeiwu_com5年前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设置matplotlib.plot的坐标轴刻度间隔以及刻度范围

Python设置matplotlib.plot的坐标轴刻度间隔以及刻度范围

一、用默认设置绘制折线图 import matplotlib.pyplot as plt x_values=list(range(11)) #x轴的数字是0到10这11个整数 y...

使用WingPro 7 设置Python路径的方法

使用WingPro 7 设置Python路径的方法

Python使用称为Python Path的搜索路径来查找使用import语句导入代码的模块。大多数代码只会汇入已经默认路径上的模块,通过安装到Python的Python标准库的例子模块...

Python常见读写文件操作实例总结【文本、json、csv、pdf等】

本文实例讲述了Python常见读写文件操作。分享给大家供大家参考,具体如下: 读写文件 读写文件是最常见的IO操作,python内置了读写文件的函数,用法和c是兼容的. 读写文件前,我们...

Python利用IPython提高开发效率

Python利用IPython提高开发效率

一、IPython 简介 IPython 是一个交互式的 Python 解释器,而且它更加高效。 它和大多传统工作模式(编辑 -> 编译 -> 运行)不同的是, 它采用的工...

python内置函数sorted()用法深入分析

本文实例讲述了python内置函数sorted()用法。分享给大家供大家参考,具体如下: 列表对象提供了sort()方法支持原地排序,而内置函数sorted()不支持原地操作只是返回新的...