0

如何从每个字符串中收集多个字符串print作为一个函数写入另一个文件?(如果我的措辞正确)

这是我所拥有的:

 heart_max,heart_min = find_max_min (wanted_tuples, 0,1)
print ('Heart: {}  {:.1f}   {}   {:.1f}'.format(heart_min[1],heart_min[0],heart_max[1],heart_max[0]))

#
mv_max,mv_min = find_max_min (wanted_tuples, 0,2)
print ('Motor: {}  {:.1f} {}  {:.1f}'.format(mv_min[1],mv_min[0],mv_max[1],mv_max[0]))

#
birth_max,birth_min = find_max_min (wanted_tuples, 0,3)
print ('Birth:  {}   {:.1f}   {}  {:.1f}'.format(birth_min[1],birth_min[0],birth_max[1],birth_max[0]))

#
smoke_max,smoke_min = find_max_min (wanted_tuples, 0,4)
print ('Smoking: {}  {:.1f}   {}   {:.1f}'.format(smoke_min[1],smoke_min[0],smoke_max[1],smoke_max[0]))

#
ob_max,ob_min = find_max_min (wanted_tuples, 0,5)
print ('Obesity: {}   {:.1f}   {}   {:.1f}'.format(ob_min[1],ob_min[0],ob_max[1],ob_max[0])) 


outstring = {'Heart:'' {}  {:.1f}   {}  {:.1f}'.format(heart_min[1],heart_min[0],heart_max[1],heart_max[0])},
             'Motor:   {}  {:.1f}   {}  {:.1f}'.format(mv_min[1],mv_min[0],mv_max[1],mv_max[0])),
             'Birth:   {}  {:.1f}   {}  {:.1f}'.format(birth_min[1],birth_min[0],birth_max[1],birth_max[0])),
             'Smoking: {}  {:.1f}   {}  {:.1f}'.format(smoke_min[1],smoke_min[0],smoke_max[1],smoke_max[0])),
             'Obesity: {}  {:.1f}   {}  {:.1f}'.format(ob_min[1],ob_min[0],ob_max[1],ob_max[0]))}

然后将结果写入这个文件

f_write = open('best_and_worst.txt', 'w') #creates the file
try:
    f_write.writelines(outstring)

finally:
        f_write.close()

我像这样格式化字符串,以便在运行时可以使输出看起来像这样:

                                       Min                          Max 
Heart:        Minnesota                1.8          Missouri        26.4
Motor:        Washington               2.8          Colorado        34.6
Birth:        Ohio                     4.4          New York        43.2
Smoking:      Utah                     6.1          Ohio            44.3
Obesity:      Michigan                19.1          Mississippi     37.3

我整个长程序运行良好,没有错误。只是出于某种原因,我对如何做到这一点持空白。任何帮助或指导表示赞赏。

4

1 回答 1

2

不要使用print(),只需将字符串存储在列表中并将字符串写入文件:

output = []

heart_max,heart_min = find_max_min (wanted_tuples, 0,1)
output.append('Heart: {}  {:.1f}   {}   {:.1f}'.format(heart_min[1],heart_min[0],heart_max[1],heart_max[0]))

mv_max,mv_min = find_max_min (wanted_tuples, 0,2)
output.append('Motor: {}  {:.1f} {}  {:.1f}'.format(mv_min[1],mv_min[0],mv_max[1],mv_max[0]))

# etc.

with open('best_and_worst.txt', 'w') as f_write:
    f_write.write('\n'.join(output))
于 2013-03-11T21:44:59.820 回答