What is the best way to print a table with delimiters in Python

你。 提交于 2019-12-05 01:53:18

问题


I want to print a table mixed with string and float values, as tab delimited output printout. Sure I can get the job done:

>>> tab = [['a', 1], ['b', 2]]
>>> for row in tab:
...     out = ""
...     for col in row:
...             out = out + str(col) + "\t"
...     print out.rstrip()
... 
a   1
b   2

But I have a feeling there is a better way to do it in Python, at least to print each row with specified delimiter, if not the whole table. Little googling (from here) and it is already shorter:

>>> for row in tab:
...     print "\t".join([str(col) for col in row])
... 
a   1
b   2

Is there still a better, or more Python-ish, way to do it?


回答1:


Your shorter solution would work well as something quick and dirty. But if you need to handle large amounts of data, it'd be better to use csv module:

import sys, csv
writer = csv.writer(sys.stdout, delimiter="\t")
writer.writerows(data)

The benefit of this solution is that you may easily customize all aspects of output format: delimiter, quotation, column headers, escape sequences...




回答2:


I don't think it's going to get much better than your second code snippet... maybe, if you really want,

print "\n".join("\t".join(str(col) for col in row) for row in tab)



回答3:


import sys
import csv

writer = csv.writer(sys.stdout, dialect=csv.excel_tab)
tab = [['a', 1], ['b', 2]]
writer.writerows(tab)



回答4:


Please do not use concatanation because it creates a new string every time. cStringIO.StringIO will do this kind of job much more efficiently.




回答5:


It depends on why you want to output like that, but if you just want to visually reference the data you might want to try the pprint module.

>>> import pprint
>>> for item in tab:
...     pprint.pprint(item, indent=4, depth=2)
...
['a', 1]
['b', 2]
>>>
>>> pprint.pprint(tab, indent=4, width=1, depth=2)
[   [   'a',
        1],
    [   'b',
        2]]
>>>



回答6:


The prettytable library may be useful. It also helps maintain the column alignment and allows additional style customizations.

Example:

# Ref: https://code.google.com/archive/p/prettytable/

import prettytable

# Read the input csv file
with open("input.csv", "r") as input_file:
    table = prettytable.from_csv(input_file)

# Optionally, change the default style
table.set_style(prettytable.PLAIN_COLUMNS)
table.align = "l"
table.valign = "t"

# Write the output ASCII text file
with open("output.txt", "w") as output_file:
    print("{}".format(table.get_string()), file=output_file)

# Optionally, write the output html file
with open("output.html", "w") as output_file:
    print("{}".format(table.get_html_string()), file=output_file)


来源:https://stackoverflow.com/questions/583557/what-is-the-best-way-to-print-a-table-with-delimiters-in-python

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