Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
102 views
in Technique[技术] by (71.8m points)

python - How do I save results of a "for" loop into a single variable?

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_temp(x))

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

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

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

All in all, this for loop produces 12 lines.

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

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...