我有以下代码片段:
techs = ["name1", "name2", "name3", "name4", "name5", "name6", "name7", "name8", "name9"];
for tech in techs:
current_tech = get_ticket_count(FHD_start,BHN_end,tech)
tech_total = str(current_tech[0])
tech_average = current_tech[1]
print "\n"
print (tech)
print "Total: " + tech_total
print "Average: " + tech_average
输出如下:
name1
Total: 69
Average: 17
name2
Total: 30
Average: 7
name3
Total: 0
Average: 0
......等等。
最终目标是将结果通过电子邮件发送到表中,但是现在我正在尝试弄清楚如何将其正确输出到表中。类似的东西:
Tech | Total | Average
name1 | 69 | 17
name2 | 30 | 7
name3 | 0 | 0
或只是像那样组织的东西。我不知道从哪里开始。我发现的文章和答案都与我不读的CSV有关。
感谢任何帮助。
答案 0 :(得分:1)
尝试使用tabulate包。它支持很多输出格式,并且非常易于使用
示例:
import tabulate
headers = ['Tech', 'Total', 'Average']
data = [['name1', 69, 17], ['name2', 30, 7], ['name3', 0, 0]]
print(tabulate.tabulate(data, headers, tablefmt='presto'))
它将打印出来:
Tech | Total | Average
--------+---------+-----------
name1 | 69 | 17
name2 | 30 | 7
name3 | 0 | 0
或者,如果您使用,请说tablefmt='simple'
:
Tech Total Average
------ ------- ---------
name1 69 17
name2 30 7
name3 0 0
等等
答案 1 :(得分:0)
您可以使用自己的函数来确定每列中的最大项,然后创建一个合适的表:
def write_table(data):
col_spacer = " | " # added between columns
widths = [0] * len(data[0])
for row in data:
widths[:] = [max(widths[index], len(str(col))) for index, col in enumerate(row)]
return '\n'.join(col_spacer.join("{:<{width}}".format(col, width=widths[index]) for index, col in enumerate(row)) for row in data)
techs = ["name1", "name2", "name3", "name4", "name5", "name6", "name7", "name8", "name9"];
table = [['Tech', 'Total', 'Average']]
for tech in techs:
current_tech = get_ticket_count(FHD_start,BHN_end,tech)
tech_total = str(current_tech[0])
tech_average = current_tech[1]
table.append([tech, tech_total, tech_average])
print write_table(table)
给你:
Tech | Total | Average
name1 | 69 | 17
name2 | 30 | 7
name3 | 0 | 0
当您使用空格填充每一行时,您需要确保用于显示电子邮件的字体是固定宽度,否则由于比例间距,它仍然会显示错误。