我有一个.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列中表示)。
您正在混淆字段和字符。您必须拆分字符串并将拆分后的字符串转换为整数。
然后,您必须每天创建一个列表,因此最好使用字典来创建多个临时向量,并最终打印出每天的平均值。
(请注意,第二列是完全未使用的)
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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句