存在一个txt文件
姓名-课程-分数
张三-语文-100
李四-语文-90
张三-数学-80
李四-英语-70
使用多个函数实现
读取txt文件内容
转换为列表嵌套字典形式[{‘姓名’:‘张三’,平均成绩:90},{.。。}]
li = []
with open(‘woniu.txt’,‘r’,encoding= ‘utf8’) as f:
contents = f.readlines()
f.close()
for i in range(1,len(contents)):
dict1 = {}
dict1[‘姓名’] = contents[i].strip().split(’-’)[0]
dict1[‘课程’] = contents[i].strip().split(’-’)[1]
dict1[‘分数’] = contents[i].strip().split(’-’)[2]
li.append(dict1)
print(li)
dict2 = {}
for d in li:
if d[‘姓名’] not in dict2 :
dict2[d[‘姓名’]] = int(d[‘分数’])
else:
dict2[d[‘姓名’]] += int(d[‘分数’])
print(dict2)
for key in dict2.keys():
count = 0
for d in li:
if d[‘姓名’] == key:
count += 1
dict2[key] = dict2[key]/count
print(dict2)
li2 = []
for k,v in dict2.items():
li2.append({‘姓名’:k,‘平均分数’:v})
print(li2)