[英]What is the best way to print a list with 3 sublists to a file in python?
[英]What is the best way to print a table with delimiters in Python
我想打印一個混合了字符串和浮點值的表格,作為制表符分隔的 output 打印輸出。 當然我可以完成工作:
>>> 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 中有更好的方法,如果不是整個表,至少要打印帶有指定分隔符的每一行。 谷歌搜索(從這里),它已經更短了:
>>> for row in tab:
... print "\t".join([str(col) for col in row])
...
a 1
b 2
還有更好的,或者更 Python 的方式來做到這一點嗎?
您較短的解決方案可以作為快速而骯臟的解決方案。 但如果需要處理大量數據,最好使用csv
模塊:
import sys, csv
writer = csv.writer(sys.stdout, delimiter="\t")
writer.writerows(data)
此解決方案的好處是您可以輕松自定義 output 格式的所有方面:分隔符、引號、列標題、轉義序列...
我認為它不會比你的第二個代碼片段好得多......也許,如果你真的想要,
print "\n".join("\t".join(str(col) for col in row) for row in tab)
import sys
import csv
writer = csv.writer(sys.stdout, dialect=csv.excel_tab)
tab = [['a', 1], ['b', 2]]
writer.writerows(tab)
Prettytable庫可能很有用。 它還有助於維護列 alignment 並允許額外的樣式自定義。
例子:
# 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)
請不要使用串聯,因為它每次都會創建一個新字符串。 cStringIO.StringIO 將更有效地完成此類工作。
這取決於您為什么要 output 那樣,但如果您只是想直觀地參考數據,您可能想嘗試pprint模塊。
>>> 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]]
>>>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.