0

我遇到了以下问题:我想读取一个由两列组成的数据文本文件,年份和温度,并且能够计算每年的最低温度等。整个文件是这样开始的:

1995.0012 -1.34231 
1995.3030 -3.52533
1995.4030 -7.54334

依此类推,直到 2013 年。我有以下想法:

f=open('munich_temperatures_average.txt', 'r')
for line in f:
    line = line.strip()
    columns = line.split()
    year = float(columns[0])
    temperature=columns[1]
    if year-1995<1 and year-1995>0:
        print 1995, min(temperature)

有了这个,我只得到 1995 年的数据,这是我第一步想要的。在第二步中,我想计算 1995 年整个数据集的最低温度。通过使用上面的脚本,我得到了数据文件中每一行的最低温度。我尝试建立一个列表,然后附加温度,但如果我想将年份转换为整数或温度转换为浮点数等,我会遇到麻烦。

我觉得我错过了如何计算列(但不是整列)中一组值的最小值的正确想法。

有什么想法可以解决上述问题吗?我正在尝试学习 Python,但仍处于初学者阶段,所以如果有办法在不使用“高级”命令的情况下完成整个事情,我会欣喜若狂!

4

4 回答 4

0

如果你只想要年份和时间:

years,temp =[],[]
with open("f.txt") as f:
    for line in f:
        spl = line.rstrip().split()
        years.append(int(spl[0].split(".")[0]))
        temp.append(float(spl[1]))

print years,temp
[1995, 1995, 1995] [-1.34231, -3.52533, -7.54334]
于 2014-08-06T16:33:00.063 回答
0

我之前使用numpy库提交了另一种方法,考虑到您是 python 新手,这可能会令人困惑。对此感到抱歉。正如您自己提到的,您需要有 1995 年的某种记录,但您不需要为此列出清单:

mintemp1995 = None
for line in f:
    line = line.strip()
    columns = line.split()
    year = int(float(columns[0]))
    temp = float(columns[1])
    if year == 1995 and (mintemp1995 is None or temp < mintemp1995):
        mintemp1995 = temp
print "1995:", mintemp1995

注意 的转换intyear,因此您可以直接将其与 1995 以及之后的条件进行比较:

如果该变量mintemp1995以前从未设置过(None因此是数据集的第一个条目),或者当前温度低于该值,它将替换它,因此您只有最低温度的记录。

于 2014-08-06T16:33:37.293 回答
0

我可以使用正则表达式来做到这一点

import re
from collections import defaultdict

REGEX = re.compile(ur"(\d{4})\.\d+ ([0-9\-\.\+]+)")

f = open('munich_temperatures_average.txt', 'r')
data = defaultdict(list)
for line in f:
    year, temperature = REGEX.findall(line)[0]
    temperature = float(temperature)
    data[year].append(temperature)
print min(data["1995"])
于 2014-08-06T16:27:14.143 回答
0

您可以使用该csv模块,它可以很容易地阅读和操作文件的每一行:

import csv
with open('munich_temperatures_average.txt', 'r') as temperatures:
    for row in csv.reader(temperatures, delimiter=' '):
        print "year", row[0], "temp", row[1]

之后,只需在行中找到最低温度即可。请参阅 csv 模块文档

于 2014-08-06T16:28:52.973 回答