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处理图片实现图像中的像素访问

前面的一些例子中,我们都是利用Image.open()来打开一幅图像,然后直接对这个PIL对象进行操作。如果只是简单的操作还可以,但是如果操作稍微复杂一些,就比较吃力了。因此,通常我们加...

python获取文件真实链接的方法,针对于302返回码

使用模块requests 方式代码如下: import requests url_string="https://******" r = requests.head(url_st...

Python 实现文件读写、坐标寻址、查找替换功能

Python 实现文件读写、坐标寻址、查找替换功能

读文件 打开文件(文件需要存在) #打开文件 f = open("data.txt","r") #设置文件对象 print(f)#文件句柄 f.close() #关闭文件 #为了方...

python遍历数组的方法小结

本文实例总结了python遍历数组的方法。分享给大家供大家参考。具体分析如下: 下面介绍两种遍历数组的方法,一种是直接通过for in 遍历数组,另外一种是通过rang函数先获得数组长度...

详解python uiautomator2 watcher的使用方法

该方是基于uiautomator2如下版本进行验证的: PS C:\windows\system32> pip show uiautomator2 Name: uiautoma...