首页 > 解决方案 > 以下简单的文件操作程序是否有更短的代码?

问题描述

以下是问题,我已经编写了代码。有人可以缩短答案代码吗?

假设文件 studentdata.txt 包含有关学生在各种作业中获得的成绩的信息。每行都有学生的姓氏(您可以假设是一个单词)和学生获得的数字成绩。所有成绩都满分100分。学生可以在文件中多次出现。这是一个示例文件:

Arnold 90
Brown 84
Arnold 80
Cocher 77
Cocher 100

编写一个函数,将文件中的数据读入字典。然后继续提示用户输入学生的姓名。对于每个学生,它应该打印该学生的平均成绩。当用户输入不在字典中的学生姓名时停止提示。给定文件的示例运行:

Enter name: Arnold
The average for Arnold is: 85.0 
Enter name: Brown
The average for Brown is: 84.0
Enter name: Cocher
The average for Cocher is: 88.5
Enter name: Doherty
Goodbye!

这是我的代码:

import os
PATH="C:/Users/user/Desktop/studentdata.txt"
fd=open("C:/Users/user/Desktop/studentdata.txt","r")

d=fd.read()
p1=r"\b[A-za-z]+\b"
p2=r"\b[0-9]+\b"
l1=re.findall(p1,d) 
fd=open("C:/Users/user/Desktop/studentdata.txt","r")
l2=re.findall(p2,d)
d={}
for key,val in list(zip(l1,l2)):
    if key not in d:
        d[str(key)]=int(val)
    else:
        d[str(key)]+=int(val)
for key in d:
    d[key]=d[key]/l1.count(key)


while True:
    key=input("Enter name:")
    if key not in d:
        print("Goodbye!")
        break
    print("the average for "+key+" is: "+str(d[key]))

标签: pythonpython-3.x

解决方案


PATH = "C:/Users/user/Desktop/"
FILE = "studentdata.txt"
with open(PATH + FILE, 'r') as fp:
  lines = fp.readlines()
notes_with_students = {}

for line in lines:
  student = line.split()[0]
  note = line.split()[1]
  if student not in notes_with_students:
    notes_with_students.setdefault(student, [int(note), 1])
  else:
    notes_with_students[student][0] += int(note)
    notes_with_students[student][1] += 1

while True:
  student = input("Enter name: ")
  if student not in notes_with_students:
    print("Goodbye!")
    break
  print("The average for {} is: {}".format(student, notes_with_students[student][0]/notes_with_students[student][1]))

这可能很有用。


推荐阅读