从元组列表创建格式化表格

时间:2018-11-27 16:33:14

标签: python python-2.7 formatting format

我有一个看起来像这样的数据列表:

[
    (
        1,
        u'python -c \'print("ok")\'',
        u'data',
        u'python'
    ), (
        2,
        u'python -c \'print("this is some data")\'',
        u'data',
        u'python'
    )
]

此数据将从数据库中取出并以此形式显示,并且一直在增长。我想做的就是这样显示数据:

Language  |  Type  |   Payload
-------------------------------
 python   |  data  |  python -c 'print("ok")'
 python   |  data  |  python -c 'print("this is some data")'

我有一个函数可以做同样的事情,但是它并不完全符合预期:

def print_table(data, cols, width):
    n, r = divmod(len(data), cols)
    pattern = "{{:{}}}".format(width)
    line = "\n".join(pattern * cols for _ in range(n))
    last_line = pattern * r
    print(line.format(*data))
    print(last_line.format(*data[n*cols]))

如何使数据输出看起来像想要的?从答案中可以使用pandas,但我也想一种无需安装外部模块的方法

3 个答案:

答案 0 :(得分:2)

分析数据的最大宽度并使用字符串格式-稍后使用一些“创意”格式:

data = [
    (
        1,
        u'python -c \'print("ok")\'',
        u'data',
        u'python'
    ), (
        2,
        u'python -c \'print("this is some data")\'',
        u'data',
        u'python'
    )
]



def print_table(data):
    widths = {0:0, 3:len("Language"),2:len("Type"),1:len("Payload")}
    for k in data:
        for i,d in enumerate(k): 
            widths[i] = max(widths[i],len(str(d))) 
    # print(widths)

    lan, typ, pay = ["Language","Type","Payload"]
    print(f"{lan:<{widths[3]}}  |  {typ:<{widths[2]}}  |  {pay:<{widths[1]}}")
    # adjust by 10 for '  |  ' twice
    print("-" * (widths[1]+widths[2]+widths[3]+10)) 
    for k in data:
        _, pay, typ, lan = k
        print(f"{lan:<{widths[3]}}  |  {typ:<{widths[2]}}  |  {pay:<{widths[1]}}") 

输出:

Language  |  Type  |  Payload                               
------------------------------------------------------------
python    |  data  |  python -c 'print("ok")'               
python    |  data  |  python -c 'print("this is some data")'

等效的Python 2.7代码:

# w == widths - would break 79 chars/line else wise
def print_table(data):
    w = {0:0, 3:len("Language"),2:len("Type"),1:len("Payload")}
    for k in data:
        for i,d in enumerate(k): 
            w[i] = max(w[i],len(str(d))) 


    lan, typ, pay = ["Language","Type","Payload"]
    print "{:<{}}  |  {:<{}}  |  {:<{}}".format(lan, w[3], typ, w[2], pay, w[1])   
    print "-" * (w[1]+w[2]+w[3]+10) 
    for k in data:
        _, pay, typ, lan = k
        print "{:<{}}  |  {:<{}}  |  {:<{}}".format(lan, w[3], typ, w[2], pay, w[1]) 

答案 1 :(得分:1)

您可以使用pandas

import pandas as pd
data = pd.DataFrame(a, columns=['id','Payload', 'type', 'Language'])
print(data)

给您

   id                                 Payload  type Language
0   1                 python -c 'print("ok")'  data   python
1   2  python -c 'print("this is some data")'  data   python

答案 2 :(得分:1)

可处理任意数量列的解决方案:

from operator import itemgetter

data = [
    ('ID', 'Payload', 'Type', 'Language'),
    (1, u'python -c \'print("ok")\'', u'data', u'python'),
    (2, u'python -c \'print("this is some data")\'', u'data', u'python')
]


def print_table(data):
    lengths = [
        [len(str(x)) for x in row]
        for row in data
    ]

    max_lengths = [
        max(map(itemgetter(x), lengths))
        for x in range(0, len(data[0]))
    ]

    format_str = ''.join(map(lambda x: '%%-%ss | ' % x, max_lengths))

    print(format_str % data[0])
    print('-' * (sum(max_lengths) + len(max_lengths) * 3 - 1))

    for x in data[1:]:
        print(format_str % x)

print_table(data)

输出:

$ python table.py
ID | Payload                                | Type | Language |
---------------------------------------------------------------
1  | python -c 'print("ok")'                | data | python   |
2  | python -c 'print("this is some data")' | data | python   |