Python输出到表
我有以下代码片段:Python输出到表,python,Python,我有以下代码片段: 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_tec
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有关,而我不是从CSV上阅读
感谢您的帮助 尝试使用该软件包。它支持多种输出格式,并且非常易于使用
例如:
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
依此类推您可以使用自己的函数确定每列中最大的项,然后创建一个合适的表:
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)
当您使用空格填充每一行时,您需要确保用于显示电子邮件的字体是固定宽度的,否则由于间距成比例,它看起来仍然是错误的。您不想使用csv有什么原因吗?这只是一种用任何分隔符存储表的明文方式。您需要确保您的电子邮件使用固定宽度的字体。Seth-在通过电子邮件发送数据时,CSV会更容易吗?如果没有明确的示例,这更适合作为注释。@Prune,是的,很抱歉。我其实是想发表评论,但不知怎的,我把它作为一个答案贴了出来。。。我添加了示例OK,因此得到了以下结果:
print write\u table(table)name错误:当我运行时,name'write\u table'不是define
。您复制了所有脚本吗<代码>def write_table()位于顶部?叹气。我保证我会使用电脑。谢谢你的帮助!