4

印刷に問題がありますnamedtuple

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

値が整列され、それらの間にスペース(パディング)があるようにします。たとえば、次のようになります。

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使用して印刷を試みましたが、成功しませんでした。名前付きタプルで動作させることができなかったものと同じです。アイデアやサンプルコードはありますか?_asdictformat

4

2 に答える 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  )
于 2016-04-09T16:16:13.337 に答える