How do I save results of a “for” loop into a single variable?

若如初见. 提交于 2019-11-28 12:19:55

Try this

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

Now result contains the x and avg

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

You can save it to sample.pkl by

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

Then check by

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

You could simply store the results in a dictionary, pickle that and store it:

import pickle

d = {}
for x in range(1,13):
   d[x] = Boston_monthly_temp(x)
res = pickle.dumps(d)
# write res to a file
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!