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

后端 未结 2 1015
傲寒
傲寒 2020-12-03 22:57

I have a for loop:

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


        
2条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-03 23:30

    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 ...
    .....
    

提交回复
热议问题