我有一个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 was the average temperature in month number 1 in Boston, 2014: 26.787096774193547
一直到第12个月(12月):
This was the average temperature in month number 12 in Boston, 2014: 38.42580645161291.
总而言之,这个for循环产生了12行。
但是,我无法弄清楚如何存储此结果"对于"循环到单个变量,如(output_number_one)。
我试图将结果存储到单个变量中,因此我可以将变量(及其内容)转储/写入pickle文件,名为:
output.pkl
答案 0 :(得分:5)
试试这个
result = []
for x in range(1,13):
result.append((x, Boston_monthly_temp(x)))
现在结果包含x
和avg
for x, avg in result:
print ("This was the average temperature in month number " + str(x) + " in Boston, 2014: ", avg)
您可以通过
将其保存到sample.pkl
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 ...
.....
答案 1 :(得分:4)
您可以简单地将结果存储在字典中,然后将其存储并存储:
import pickle
d = {}
for x in range(1,13):
d[x] = Boston_monthly_temp(x)
res = pickle.dumps(d)
# write res to a file