在Python中打印带分隔符的表的最好方法是什么 [英] What is the best way to print a table with delimiters in Python

查看:664
本文介绍了在Python中打印带分隔符的表的最好方法是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想打印一个混合有字符串和浮点值的表,作为制表符分隔的输出打印输出。确定我可以完成这项工作:

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

但我有一种感觉,有一个更好的方法来做它在Python,至少打印每个行与指定的分隔符,如果不是整个表。小搜索(来自此处),且已缩短:

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


$ b b $ b

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

推荐答案

你的较短的解决方案会很快的和脏的工作。但是如果你需要处理大量的数据,最好使用 csv 模块:

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...

这篇关于在Python中打印带分隔符的表的最好方法是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆