下面的简单文件操作程序是否有较短的代码?

2024-10-02 08:14:39 发布

您现在位置:Python中文网/ 问答频道 /正文

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

Suppose the file studentdata.txt contains information on grades students earned on various assignments. Each line has the last name of a student (which you can assume is one word) and the numeric grade that student received. All grades are out of 100 points. Students can appear multiple times in the file. Here’s a sample file:

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]))

Tags: thekeynameintxtforis学生
1条回答
网友
1楼 · 发布于 2024-10-02 08:14:39
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]))

这可能很有用

相关问题 更多 >

    热门问题