【问题标题】:How do I save results of a "for" loop into a single variable?如何将“for”循环的结果保存到单个变量中?
【发布时间】:2015-03-24 05:28:45
【问题描述】:

我有一个 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 个月(十二月):

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

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

但是,我不知道如何将这个“for”循环的结果存储到单个变量中,例如 (output_number_one)。

我正在尝试将结果存储到单个变量中,因此我可以将变量(及其内容)转储/写入到 pickle 文件中,称为:

output.pkl

【问题讨论】:

  • 由于“保存到变量”,您可以放弃 print(因为它用于副作用而不是值生成)在这种情况下,List Comprehension 将是一种惯用方法(该链接还显示了如何显式构建列表)。

标签: python persistence pickle


【解决方案1】:

试试这个

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

现在结果包含xavg

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

【讨论】:

    【解决方案2】:

    您可以简单地将结果存储在字典中,然后将其腌制并存储:

    import pickle
    
    d = {}
    for x in range(1,13):
       d[x] = Boston_monthly_temp(x)
    res = pickle.dumps(d)
    # write res to a file
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-03
      • 1970-01-01
      • 1970-01-01
      • 2019-11-23
      相关资源
      最近更新 更多