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?
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...
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With