Python:打印列表作为表格列表

时间:2015-08-13 18:16:44

标签: python list

我是python的新手并且遇到了问题。我有一个文本文件,我将其读入列表,然后将其分成块或"团队"。子列表的数量是根据我想要的团队数量创建的。这一切都完成了。但我想以一种漂亮的表格格式打印出来。我调查了以下问题thisthisthis,但它们并不是我所寻找的。我甚至看过pypi模块PrettyTable和DataGrid。

我的最终名单如下:

['name9', 'name2'], ['name4', 'name11'], ['name10', 'name3'], ['name7', 'name6'], ['name5', 'name8'], ['name']]

我这样打印出来:

for i in range(len(l)):
    print "Teams{}\t\t ".format(i+1),
print
for x in itertools.izip_longest(*l, fillvalue="."):
    print "\n"
    t =  "\t\t ".join(str(i) for i in x)
    print t

结果是:

Teams1        Teams2          Teams3          Teams4          Teams5          Teams6


name9        name4       name10      name7       name5       name


name2        name11      name3       name6       name8       .

有什么方法可以得到这样的输出:

Team 1      Team 2      Team 3      Team 4      Team 5      Team 6
-------------------------------------------------------------------
name9       name4       name10      name7       name5       name
name2       name11      name3       name6       name8       .

并恰好对齐它们?

6 个答案:

答案 0 :(得分:6)

或者,如果您不想使用第三方库:

from itertools import izip_longest

data = [['name9', 'name2'], ['name4', 'name11'], ['name10', 'name3'], ['name7', 'name6'], ['name5', 'name8'], ['name']]

length = max(len(name) for names in data for name in names)
gutter = 5

format_string = '{{:<{}}}'.format(length + gutter)

print ''.join(format_string.format('Team {}'.format(x)) for x in range(len(data)))
print '-' * len(data) * (length + gutter)
for names in izip_longest(*data, fillvalue='.'):
    print ''.join(format_string.format(name) for name in names)

产地:

Team 0     Team 1     Team 2     Team 3     Team 4     Team 5
------------------------------------------------------------------
name9      name4      name10     name7      name5      name
name2      name11     name3      name6      name8      .

答案 1 :(得分:1)

使用prettytable

from prettytable import PrettyTable

teams = ['team%d'%(x+1) for x in range(len(l)) ]
x = PrettyTable(teams)
for i in itertools.izip_longest(*l, fillvalue="."):
    x.add_row(i)
x.vertical_char = ' '
x.junction_char = '-'

print(x)

---------------------------------------------------
  team1   team2    team3    team4   team5   team6  
---------------------------------------------------
  name9   name4    name10   name7   name5    name  
  name2   name11   name3    name6   name8     .    
---------------------------------------------------

lines = x.get_string().split('\n')
output = '\n'.join(lines[1:-1])
print(output)

team1   team2    team3    team4   team5   team6  
---------------------------------------------------
name9   name4    name10   name7   name5    name  
name2   name11   name3    name6   name8     .  

答案 2 :(得分:1)

这使用字符串方法ljust()来左对齐每个项目,而不是依赖于多个标签和自定义print结尾(放在解释器中的if块中,这样您就可以看到整个表格一次):

>>> if 1:
...     print "".join(  ("Teams" + str(i+1)).ljust(10) for i in xrange(10))
...     print
...     for x in itertools.izip_longest(*l, fillvalue="."):
...             print "".join(str(i).ljust(10) for i in x)
...
Teams1    Teams2    Teams3    Teams4    Teams5    Teams6    Teams7    Teams8    Teams9    Teams10

name9     name4     name10    name7     name5     name
name2     name11    name3     name6     name8     .

答案 3 :(得分:1)

可以通过逐行构建所有内容来完成:

teams = {'Teams 1': ['name9', 'name2'], 
         'Teams 2': ['name4', 'name11'],
        'Teams 3':['name10']}

print teams

line1 = []
line2 = []
line3 = []

for key, value in teams.iteritems():
    line1.append(key)
    line2.append(value[0])
    if len(value) == 2:
        line3.append(value[1])
    else:
        line3.append(".")

def build_row(line, max_width=20):
    linef = ''
    for i in line:
        spaces = max_width - len(i)
        linef += i
        linef += ' '*spaces
    return linef

row1 = build_row(line1)
print row1
print '-'*len(row1)
print build_row(line2)
print build_row(line3)

>>> 
Teams 1             Teams 3             Teams 2             
------------------------------------------------------------
name9               name10              name4               
name2               .                   name11    

答案 4 :(得分:1)

为什么不进行字符串格式化https://docs.python.org/2/library/string.html#format-specification-mini-language

l = [['name9', 'name2'], ['name4', 'name11'], ['name10', 'name3'], ['name7', 'name6'], ['name5', 'name8'], ['name']]
cell = "{:<10}"

for i in range(len(l)):
    hdr = "Teams{}".format(i+1)
    print(cell.format(hdr), end="")
print("\n")
print("-"*60)      
for x in zip_longest(*l, fillvalue="."):    
    t =  "".join(cell.format(i) for i in x)
    print( t + "\n")
抱歉,我使用的是python 3.4,因此我的打印需要()

答案 5 :(得分:0)

试试tabviewhttps://pypi.python.org/pypi/tabview/

它既可以用作cli工具,也可以用作python模块:

import tabview as t
a = [["a","b","c"], ["d","e","f"]]
t.view(a)