如何从测量列表中提取每日平均温度?

时间:2016-09-21 14:01:02

标签: python-3.x

我有一个.txt这样的文件:

#day hr T 0.1 d.C.
1    1  137
1    2  124
1    3  130
1    4  128
1    5  141
1    6  127
1    7  153
1    8  137
1    9  158
1    10 166
...
2   1   136
2   2   135
2   3   135
2   4   132
and so on...

我写了这段代码:

import sys

NUMBEROFDAYS = []
NUMBEROFHOURS = []
Temp = []

for line in sys.stdin:
    x = (line[0:2])
    NUMBEROFDAYS.append(x)

我得到的是:

['#d', '1\t', '1\t', '1\t', '1\t', '1\t', '1\t', '1\t', '1\t', '1\t',   and it goes on...

但是我需要从文本中提取相关的整数。 我该怎么做?

我的最终目标是计算每天的平均温度(温度在第3列中表示)。

2 个答案:

答案 0 :(得分:1)

由于您需要按天(第一列)对数据进行分组,这似乎是itertools'groupby()的典型案例:

from itertools import groupby

# first check if all characters in the line are integers:
valid = [l for l in open("/path/to/file.txt").readlines() if "".join(l.split()).isdigit()]
# split valid lines into numbers
data = [[int(n) for n in line.split()] for line in valid]
# group data by day (first number of the line)
day_data = [[item, list(records)] for item, records in groupby(data, key = lambda r: r[0])]
for day in day_data:
    temps = day[1]
    print(day[0], sum([r[2] for r in temps])/float(len(temps)))

使用您的行,这将输出:

1 140.1
2 134.5

解释

  • 首先,我们将文本文件作为行列表阅读:

    open("/path/to/file.txt").readlines()
    
  • 我们在删除所有空格后检查所有字符是否为整数:

     if "".join(l.split()).isdigit()
    
  • 然后我们将每个有效行拆分为三个整数的列表:

    data = [[int(n) for n in line.split()] for line in valid]
    
  • 然后我们使用groupby按天分组数据(这是每行的第一个整数):

    day_data = [[item, list(records)] for item, records in groupby(data, key = lambda r: r[0])]
    

    这将为我们提供两条记录,每天一条:

    1, [[1, 1, 137], [1, 2, 124], [1, 3, 130], [1, 4, 128], [1, 5, 141], [1, 6, 127], [1, 7, 153], [1, 8, 137], [1, 9, 158], [1, 10, 166]
    

    2, [[2, 1, 136], [2, 2, 135], [2, 3, 135], [2, 4, 132]
    
  • 随后,我们打印当天,然后打印特定日期第三列平均值

    for day in day_data:
        temps = day[1]
        print(day[0], sum([r[2] for r in temps])/float(len(temps)))
    

答案 1 :(得分:0)

你正在混淆字段和字符。您必须拆分字符串并将拆分的字符串转换为整数。

然后,你必须每天创建一个列表,所以最好使用字典创建几个临时向量,最后打印每天的平均值。

(请注意,第2列完全未使用)

import sys

from collections import defaultdict

d = defaultdict(lambda : list()) # dictionary: key=day, values=temp list

sys.stdin.readline() # get rid of the title
for line in sys.stdin:
    # for each line, split it (to remove blanks, so byebye tabs and convert to integer, create a list with that: list comprehension)
    x = [int(x) for x in line.split()]
    d[x[0]].append(x[2])   # add temperature to each day

for day,temps in sorted(d.items()):
    print("day {}, average temp {}".format(day,float(sum(temps))/len(temps)))

结果:

day 1, average temp 140.1
day 2, average temp 134.5
相关问题