python Pretty printing a list in a tabular format [closed]

落花浮王杯 提交于 2019-12-13 05:18:28

问题


I am referring to a post here Pretty printing a list in a tabular format

mylist = [ ( (12, 47, 4, 574862, 58, 7856), 'AGGREGATE_VALUE1'),
           ( (2, 75, 757, 8233, 838, 47775272785), 'AGGREG2'),
           ( (4144, 78, 78965, 778, 78578, 2), 'AGGREGATE_VALUE3')]

header = ('Price1','Price2','reference','XYD','code','resp','AGGREG values')

longg = dict(zip((0,1,2,3,4,5,6),(len(str(x)) for x in header)))

for tu,x in mylist:
    longg.update(( i, max(longg[i],len(str(el))) ) for i,el in enumerate(tu))
    longg[6] = max(longg[6],len(str(x)))
fofo = ' | '.join('%%-%ss' % longg[i] for i in xrange(0,7))

print '\n'.join((fofo % header,
                 '-|-'.join( longg[i]*'-' for i in xrange(7)),
                 '\n'.join(fofo % (a,b,c,d,e,f,g) for (a,b,c,d,e,f),g in mylist)))

I want to replace '\n'.join(fofo % (a,b,c,d,e,f,g) for (a,b,c,d,e,f),g in mylist))) with something dynamic. For example range1 = ', '.join(map(chr, range(97, 97+7))) which gives me a,b,c,d,e,f,g

so the line will look '\n'.join(fofo % (range1) for (a,b,c,d,e,f),g in mylist)))

but gives me:

TypeError: not enough arguments for format string


回答1:


The error is that range1 is a string while you expect to have variables. You perhaps may use something like eval?

So you can do:

    '\n'.join(fofo % eval(range1) for (a,b,c,d,e,f),g in mylist)

Or to avoid refering to several vars:

    '\n'.join(fofo % (tuple(x[0])+(x[1],)) for x in mylist)

Each element of mylist is made by a tuple containing a tuple and a string like ((a,b..), "string"). So if you consider x containing such data, tuple(x[0]) designate the first tuple while (x[1],) make a tuple with single element that is the string. Finally tuple(x[0])+(x[1],) will create only one tuple with all elements like:

    x = ((0, 1, 2), "a")
    tuple(x[0])+(x[1],)  #is equivalent to (0, 1, 2, "a")

This will work with ((0, 1, 2, 3, 4), "a"), or any number of element in the inside tuple.



来源:https://stackoverflow.com/questions/23415357/python-pretty-printing-a-list-in-a-tabular-format

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!