如何在列中打印嵌套的python列表 [英] How to print a nested python list in columns

查看:50
本文介绍了如何在列中打印嵌套的python列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个生成python列表的程序,该列表的输出是嵌套列表:列表的列表[名称,地址,电话号码],我希望能够以列格式打印.似乎在说明问题时这是一个非常简单的想法,但是我一直无法找到一种简单的方法来从列表中提取数据.如果我打印(列表),则列表中的每个项目都会得到如下内容:['name','address','phone number'],等等.我在Windows平台上使用Python 3.注意:(我目前不是OOP程序员)

I have a program that produces a python list as its output the list is a nested list: A list of the list [name, address, phone number] which I wish to be able to print in a columnar format. It seems upon stating the question to be a very simple Idea, but I have been unable to find a simple way to extract the data from the list. If I print(list), I get something like this: ['name','address','phone number'], etc. for each item in the list. I'm using Python 3 on a windows platform. Note: I am not a OOP programmer(at this point)

关于条例草案

推荐答案

prettytable 可以产生非常漂亮的ASCII表.教程中的示例:

from prettytable import PrettyTable

x = PrettyTable(["City name", "Area", "Population", "Annual Rainfall"])
x.align["City name"] = "l" # Left align city names
x.add_row(["Adelaide",1295, 1158259, 600.5])
x.add_row(["Brisbane",5905, 1857594, 1146.4])
x.add_row(["Darwin", 112, 120900, 1714.7])
x.add_row(["Hobart", 1357, 205556, 619.5])
x.add_row(["Sydney", 2058, 4336374, 1214.8])
x.add_row(["Melbourne", 1566, 3806092, 646.9])
x.add_row(["Perth", 5386, 1554769, 869.4])
print x

应该打印这样的东西

+-----------+------+------------+-----------------+
| City name | Area | Population | Annual Rainfall |
+-----------+------+------------+-----------------+
| Adelaide  | 1295 |  1158259   |      600.5      |
| Brisbane  | 5905 |  1857594   |      1146.4     |
| Darwin    | 112  |   120900   |      1714.7     |
| Hobart    | 1357 |   205556   |      619.5      |
| Sydney    | 2058 |  4336374   |      1214.8     |
| Melbourne | 1566 |  3806092   |      646.9      |
| Perth     | 5386 |  1554769   |      869.4      |
+-----------+------+------------+-----------------+

使该示例适合您的用例应该很简单.

Adapting this example for your use-case should be trivial.

这篇关于如何在列中打印嵌套的python列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆