Python 如何将“for”循环的结果保存到单个变量中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29225619/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 04:14:45  来源:igfitidea点击:

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

pythonpersistencepickle

提问by Python noob

I have a for loop:

我有一个 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))

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

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

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

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

一直到第 12 个月(12 月):

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

All in all, this for loop produces 12 lines.

总而言之,这个 for 循环产生 12 行。

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

但是,我无法弄清楚如何将此“for”循环的结果存储到单个变量中,例如 (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

回答by Saksham Varma

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

回答by itzMEonTV

Try this

尝试这个

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

Now result contains the xand avg

现在结果包含xavg

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

你可以将它保存到sample.pkl

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