栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python 表格打印代码实例解析

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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)

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/23679.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号