Printing tabular data in Python

ぃ、小莉子 提交于 2019-11-27 03:23:39

问题


What's the best way to print tabular data in Python? Say the data is in a 2D list and I want to create a smart looking table. What I actually have is a list of dictionaries and I want to print an intersection depending on values in the dictionaries. Something like

for val1 in my_dict:
   for val2 in my_dict:
    if val1['a'] > val2['a']:
      print 'x'

but in such a way that each column is fixed width. Writter and formatter classes seem like something in the realm of possibility, but still look complex to use when compared to, say, Perl's formatter.

Are there any existing implementations or do I have to write my own?


回答1:


Do you know about PyPi?

DataGrid and PrettyTable seem like two good alternatives I found with a brief search. You may have to assemble the data in the format you want it (with "x" for when your condition is true) before sending it to the routines provided.




回答2:


print "%20s" % somevar 

Will print the value 'somevar' and use up to 20 spaces. Add a comma behind the print statement in order to avoid the line-break - and of course: read the string formatting operations docs on the '%' operator




回答3:


Here are two ways to write a table of squares and cubes:

for x in range(1, 11):
    print repr(x).rjust(2), repr(x*x).rjust(3),print repr(x*x*x).rjust(4)

for x in range(1,11):
    print '{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x)

Check this for details.



来源:https://stackoverflow.com/questions/5122347/printing-tabular-data-in-python

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