如何保存"for"广告的结果循环成一个变量? [英] How do I save results of a "for" loop into a single variable?

查看:73
本文介绍了如何保存"for"广告的结果循环成一个变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个for循环:

for x in range(1,13):
   print ("This was the average temperature in month number " + str(x) + " in Boston, 2014: ", Boston_monthly_temp(x))

这将打印出2014年波士顿的平均每月温度,例如:

This prints out the average monthly temperatures in Boston in 2014, such as:

This was the average temperature in month number 1 in Boston, 2014:  26.787096774193547

一直到第12月(12月):

all the way up until Month Number 12 (December):

This was the average temperature in month number 12 in Boston, 2014:  38.42580645161291.

总而言之,此for循环产生12行.

All in all, this for loop produces 12 lines.

但是,我不知道如何将"for"循环的结果存储到单个变量中,例如(output_number_one).

However, I can't figure out how to store the results of this "for" loop into a single variable, like (output_number_one).

我试图将结果存储到单个变量中,所以我可以将变量(及其内容)转储/写入到一个名为以下内​​容的pickle文件中:

I'm trying to store the results into a single variable, so I can dump / write the variable (and its contents) into a pickle file, called:

output.pkl

推荐答案

尝试一下

result = []
for x in range(1,13):
    result.append((x, Boston_monthly_temp(x)))

现在结果包含xavg

for x, avg in result:
    print ("This was the average temperature in month number " + str(x) + " in Boston, 2014: ", avg)

您可以将其保存到sample.pkl,方法是

You can save it to sample.pkl by

import pickle
pickle.dump(result, open("sample.pkl","w"))

然后检查

res = pickle.load(open('sample.pkl'))
>>>for i in res:
       print i
This was the average temperature ...
This was the average temperatu ...
.....

这篇关于如何保存"for"广告的结果循环成一个变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆