您当前的位置:首页 > IT编程 > python
| C语言 | Java | VB | VC | python | Android | TensorFlow | C++ | oracle | 学术与代码 | cnn卷积神经网络 | gnn | 图像修复 | Keras | 数据集 | Neo4j | 自然语言处理 | 深度学习 | 医学CAD | 医学影像 | 超参数 | pointnet | pytorch | 异常检测 | Transformers | 情感分类 | 知识图谱 |

自学教程:python3美化表格数据输出结果的实现代码

51自学网 2021-10-30 22:44:49
  python
这篇教程python3美化表格数据输出结果的实现代码写得很实用,希望能帮到您。

技术背景

在前面一篇博客中我们介绍过关于python的表格数据处理方案,这其中的工作重点就是对表格类型的数据进行梳理、计算和展示,本文重点介绍展示这个方面的工作。首先我们看一个案例,定义一个数组形式的表格数据:

[dechin@dechin-manjaro table]$ ipythonPython 3.8.5 (default, Sep  4 2020, 07:30:14) Type 'copyright', 'credits' or 'license' for more informationIPython 7.19.0 -- An enhanced Interactive Python. Type '?' for help.In [1]: table=[('a',1,2,3),('b',2,3,4)]In [2]: print(table)[('a', 1, 2, 3), ('b', 2, 3, 4)]

当我们直接打印这个表格数据的时候,发现效果非常的难看。虽然我们可以从这个表格中获取到同样的信息,但是这种数据展示的方法对于我们直接从打印输出中获取数据是非常不利的。

使用tabulate美化表格输出

首先介绍一个工具tabulate,可以直接打印数组格式的表格数据,并且有多种输出格式可选。安装方法同样可以用pip来进行管理:

[dechin@dechin-manjaro table]$ python3 -m pip install tabulateRequirement already satisfied: tabulate in /home/dechin/anaconda3/lib/python3.8/site-packages (0.8.9)

安装很容易,也没有其他依赖。接下来我们用ipython来展示一些基本用法:

[dechin@dechin-manjaro table]$ ipythonPython 3.8.5 (default, Sep  4 2020, 07:30:14) Type 'copyright', 'credits' or 'license' for more informationIPython 7.19.0 -- An enhanced Interactive Python. Type '?' for help.In [1]: from tabulate import tabulateIn [2]: import numpy as npIn [3]: header=['index']+list(range(4)) # 表头的定义In [4]: headerOut[4]: ['index', 0, 1, 2, 3]In [8]: table=[('Alice',1,2,3,4),('Bob',2,3,4,5)] # 表格内容的定义In [9]: tableOut[9]: [('Alice', 1, 2, 3, 4), ('Bob', 2, 3, 4, 5)]In [11]: print(tabulate(table,headers=header,tablefmt='grid')) # 用grid的格式打印表格内容+---------+-----+-----+-----+-----+| index   |   0 |   1 |   2 |   3 |+=========+=====+=====+=====+=====+| Alice   |   1 |   2 |   3 |   4 |+---------+-----+-----+-----+-----+| Bob     |   2 |   3 |   4 |   5 |+---------+-----+-----+-----+-----+In [12]: print(tabulate(table,headers=header,tablefmt='fancy_grid')) # 用fancy_grid的格式打印╒═════════╤═════╤═════╤═════╤═════╕│ index   │   0 │   1 │   2 │   3 │╞═════════╪═════╪═════╪═════╪═════╡│ Alice   │   1 │   2 │   3 │   4 │├─────────┼─────┼─────┼─────┼─────┤│ Bob     │   2 │   3 │   4 │   5 │
Python生成九宫格图片的示例代码
深度学习小工程练习之tensorflow垃圾分类详解
万事OK自学网:51自学网_软件自学网_CAD自学网自学excel、自学PS、自学CAD、自学C语言、自学css3实例,是一个通过网络自主学习工作技能的自学平台,网友喜欢的软件自学网站。