Python 中的命名元组格式化/漂亮打印

4

遇到了namedtuple打印问题:

Info = namedtuple('Info', ['type', 'value', 'x', 'y'])

这样可以使值对齐,并在它们之间留出空白(padding),例如:

Info( type='AAA',    value=80000,   x=16.4,   y=164.2 )
Info( type='A',      value=78,      x=1.5,    y=11.3  )
Info( type='ABBCD',  value=554,     x=11.7,   y=10.1  )
Info( type='AFFG',   value=1263,    x=121.3,  y=12.8  )

理想情况下,没有逗号。 我尝试过使用pprint和使用_asdict打印,但没有成功,如这里所建议的那样。对于命名元组,format也是同样的情况。 有什么想法或示例代码吗?

你为什么想要那个? - jonrsharpe
1
我正在终端上打印一些结果,需要这些结果易读且美观。此外,主要想法是将这个漂亮格式的命名元组结果输出到一个文件中。 - Yannis
我认为那既不友善也不美观! - jonrsharpe
1
我能理解你的意思,但是可以说,由于它具有类似表格的格式,因此阅读起来略微更清晰。如果有一种方法可以在终端上模仿它,并将其写入文本文件中,那就太好了。 - Yannis
3
也许一些用于打印纯文本表格的库可以帮助你?https://pypi.python.org/pypi/terminaltables - ThiefMaster
1
问题在于当第一个项目打印时,它需要知道后续项目的信息,以便确定缩进量。因此,您必须将所有内容作为集合打印,而不能仅打印一个。这很丑陋! - wim
2个回答

5

这是我对命名元组实现的漂亮打印:

def prettyprint_namedtuple(namedtuple,field_spaces):
    assert len(field_spaces) == len(namedtuple._fields)
    string = "{0.__name__}( ".format(type(namedtuple))
    for f_n,f_v,f_s in zip(namedtuple._fields,namedtuple,field_spaces):
        string+= "{f_n}={f_v!r:<{f_s}}".format(f_n=f_n,f_v=f_v,f_s=f_s)
    return string+")"

我相信这就是你想要的输出结果:

a = Info( type='AAA',    value=80000,   x=16.4,   y=164.2 )
b = Info( type='A',      value=78,      x=1.5,    y=11.3  )
c = Info( type='ABBCD',  value=554,     x=11.7,   y=10.1  )
d = Info( type='AFFG',   value=1263,    x=121.3,  y=12.8  )

tups = [a,b,c,d]

for t in tups:
    print(prettyprint_namedtuple(t,(10, 9, 8, 6)))

输出:

Info( type='AAA'     value=80000    x=16.4    y=164.2 )
Info( type='A'       value=78       x=1.5     y=11.3  )
Info( type='ABBCD'   value=554      x=11.7    y=10.1  )
Info( type='AFFG'    value=1263     x=121.3   y=12.8  )

2

因为你需要提前知道字段宽度,所以我建议的唯一合理解决方案就是编写一个帮助函数将其转换为所需格式。

def namedtuple_to_str(t, field_widths=15):
    if isinstance(field_widths, int):
        field_widths = [field_widths] * len(t)
    field_pairs = ['{}={}'.format(field, getattr(t, field)) for field in t._fields]
    s = ' '.join('{{:{}}}'.format(w).format(f) for w,f in zip(field_widths, field_pairs))
    result = '{}( {} )'.format(type(t).__name__, s)
    return result

示例:

>>> from collections import namedtuple
>>> Info = namedtuple('Info', ['type', 'value', 'x', 'y'])
>>> t = Info(type='AAA', value=80000, x=16.4, y=164.2)
>>> 
>>> print namedtuple_to_str(t)
Info( type=AAA        value=80000     x=16.4          y=164.2         )
>>> print namedtuple_to_str(t, field_widths=11)
Info( type=AAA    value=80000 x=16.4      y=164.2     )
>>> print namedtuple_to_str(t, field_widths=[10, 20, 7, 7])
Info( type=AAA   value=80000          x=16.4  y=164.2 )

要打印这些内容的集合,可以通过使用 max(..., key=len) 预先计算所需的字段宽度来实现。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接