在python中创建漂亮的列输出 [英] Create nice column output in python
问题描述
我正在尝试在python中创建一个不错的列列表,以与我创建的命令行管理工具一起使用.
I am trying to create a nice column list in python for use with commandline admin tools which I create.
基本上,我想要一个像这样的列表:
Basicly, I want a list like:
[['a', 'b', 'c'], ['aaaaaaaaaa', 'b', 'c'], ['a', 'bbbbbbbbbb', 'c']]
要变成:
a b c
aaaaaaaaaa b c
a bbbbbbbbbb c
在这里使用普通制表符是行不通的,因为我不知道每一行中最长的数据.
Using plain tabs wont do the trick here because I don't know the longest data in each row.
这与Linux中的'column -t'相同..
This is the same behavior as 'column -t' in Linux..
$ echo -e "a b c\naaaaaaaaaa b c\na bbbbbbbbbb c"
a b c
aaaaaaaaaa b c
a bbbbbbbbbb c
$ echo -e "a b c\naaaaaaaaaa b c\na bbbbbbbbbb c" | column -t
a b c
aaaaaaaaaa b c
a bbbbbbbbbb c
我到处寻找各种python库来执行此操作,但是找不到任何有用的东西.
I have looked around for various python libraries to do this but can't find anything useful.
推荐答案
data = [['a', 'b', 'c'], ['aaaaaaaaaa', 'b', 'c'], ['a', 'bbbbbbbbbb', 'c']]
col_width = max(len(word) for row in data for word in row) + 2 # padding
for row in data:
print "".join(word.ljust(col_width) for word in row)
a b c
aaaaaaaaaa b c
a bbbbbbbbbb c
这是计算最长的数据条目以确定列宽,然后在打印每列时使用.ljust()
添加必要的填充.
What this does is calculate the longest data entry to determine the column width, then use .ljust()
to add the necessary padding when printing out each column.
这篇关于在python中创建漂亮的列输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!