我有一个.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', '1t', '1t', '1t', '1t', '1t', '1t', '1t', '1t', '1t', and it goes on...
然而,我需要从文本中提取相关的整数。我怎么做呢?
我的最终目标是计算每天的平均温度(温度在第三列中表示)。
由于需要按天(第一列)对数据进行分组,因此这似乎是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)))
您混淆了字段和字符。您必须拆分字符串并将拆分后的字符串转换为整数。
然后,你必须每天创建一个列表,所以最好使用字典来创建几个临时向量,并最终打印每天的平均值。
(注意第二列是完全未使用的)
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