Please read student information from the stScore.txt file. Then reorder the information based on the average score of each student and save the results in a new file stNew.txt (Code+result screenshot) Such as:
时间: 2023-11-22 20:54:17 浏览: 93
score.txt文件学生分数
Sure, here's the Python code to read the student information from "stScore.txt", calculate the average score for each student, reorder the information based on the average score, and save the results in a new file named "stNew.txt":
```python
# open stScore.txt file for reading
with open("stScore.txt", "r") as f:
lines = f.readlines()
# create a dictionary to store student information
students = {}
# loop through each line in the file
for line in lines:
# split the line into parts
parts = line.strip().split()
# get the student ID, name, and scores
sid, name, scores = parts[0], parts[1], parts[2:]
# convert scores to integers
scores = [int(s) for s in scores]
# calculate the average score
avg_score = sum(scores) / len(scores)
# add the student information to the dictionary
students[sid] = {"name": name, "scores": scores, "avg_score": avg_score}
# sort the students by average score in descending order
sorted_students = sorted(students.items(), key=lambda x: x[1]["avg_score"], reverse=True)
# open stNew.txt file for writing
with open("stNew.txt", "w") as f:
# loop through the sorted students
for student in sorted_students:
sid, data = student
name, scores, avg_score = data["name"], data["scores"], data["avg_score"]
# write the student information to the file
f.write(f"{sid} {name} {' '.join(map(str, scores))} {avg_score:.2f}\n")
print("Done.")
```
Here's an example of the input file "stScore.txt":
```
1001 Tom 80 90 85
1002 Jack 78 80 82
1003 Alice 90 95 92
1004 Bob 70 75 80
```
And here's an example of the output file "stNew.txt" after running the above code:
```
1003 Alice 90 95 92 92.33
1001 Tom 80 90 85 85.00
1002 Jack 78 80 82 80.00
1004 Bob 70 75 80 75.00
```
As you can see, the students are reordered based on their average score in descending order, and the average score is added at the end of each line with two decimal places.
阅读全文