tempts1.txt是:
Living Room,23
Bedroom,24
Kitchen,22
Living Room,24
Bedroom,26
Kitchen,22
Living Room,25
Bedroom,26
Kitchen,23
Living Room,24
Bedroom,26
Kitchen,23
我的问题是:我需要使用此.txt文件查找每个房间的平均值。我该如何分割房间的数目和平均数,以便可以使用以下方式找到平均温度:
dict={}
number={}
for y in (tempts1.txt) as file:
number = int(y[1])
room=y[0]
if room not in dict:
room=number
else: room+=number
for y in dict and number:
print(dict[y],':',number[y])
答案 0 :(得分:2)
这是使用简单迭代的一种方法。
演示:
from collections import defaultdict
res = defaultdict(list)
with open(filename) as infile:
for line in infile: #Iterate Each line
val = line.strip().split(",") #Split line by comma
res[val[0]].append(int(val[1]))
for k, v in res.items():
print("Room: {}, Avg: {}".format(k, sum(v)/float(len(v))))
按评论编辑 不导入
res = {}
with open(filename) as infile:
for line in infile: #Iterate Each line
val = line.strip().split(",") #Split line by comma
if val[0] not in res:
res[val[0]] = []
res[val[0]].append(int(val[1]))
for k, v in res.items():
print("Room: {}, Avg: {}".format(k, sum(v)/float(len(v))))
输出:
Room: Living Room, Avg: 24.0
Room: Kitchen, Avg: 22.5
Room: Bedroom, Avg: 25.5
答案 1 :(得分:0)
将总和存入一本字典,再计算到另一本并取平均值:
from collections import defaultdict
d = defaultdict(int)
count = defaultdict(int)
lines = txt.split('\n')
for line in lines:
sep = line.split(',')
d[sep[0]] += int(sep[1])
count[sep[0]] += 1
for k, v in d.items():
print(f'Average of {k}: {v/count[k]}')
# Average of Living Room: 24.0
# Average of Bedroom: 25.5
# Average of Kitchen: 22.5
答案 2 :(得分:0)
import csv
from collections import defaultdict
# Read data
with open('tempts1.txt') as f:
reader = csv.reader(f, delimiter=',', quotechar='"')
data_read = [[row[0], int(row[1])] for row in reader]
# Group by room (fist value)
tempratures_by_room = defaultdict(list)
for room, temperature in data_read:
tempratures_by_room[room].append(temperature)
# Output
for room, temperatures in sorted(tempratures_by_room.items()):
print('{room}: {average}'
.format(room=room,
average=float(sum(temperatures))/len(temperatures)))
给予
Bedroom: 25.5
Kitchen: 22.5
Living Room: 24.0