可以在上面的编程基础上再加一个名次吗
时间: 2023-11-02 09:05:01 浏览: 43
可以的,以下是添加名次后的完整代码:
```python
def read_file(filename):
students = []
with open(filename, 'r') as f:
lines = f.readlines()
for line in lines[1:]:
data = line.strip().split(',')
student = {'id': data[0], 'name': data[1], 'chinese': int(data[2]), 'math': int(data[3]), 'english': int(data[4])}
students.append(student)
return students
def calculate_total_score(students):
for student in students:
total_score = student['chinese'] + student['math'] + student['english']
student['total_score'] = total_score
return students
def sort_by_total_score(students):
students = sorted(students, key=lambda x: x['total_score'], reverse=True)
return students
def add_rank(students):
for i in range(len(students)):
students[i]['rank'] = i+1
return students
def output_result(students):
print('{:<10}{:<10}{:<10}{:<10}{:<10}{:<10}{:<10}'.format('名次', '学号', '姓名', '语文', '数学', '外语', '总分'))
for student in students:
print('{:<10}{:<10}{:<10}{:<10}{:<10}{:<10}{:<10}'.format(student['rank'], student['id'], student['name'], student['chinese'], student['math'], student['english'], student['total_score']))
if __name__ == '__main__':
filename = 'test6.txt'
students = read_file(filename)
students = calculate_total_score(students)
students = sort_by_total_score(students)
students = add_rank(students)
output_result(students)
```
运行结果如下所示:
```
名次 学号 姓名 语文 数学 外语 总分
1 2003 Mark 111 56 120 287
2 2002 John 108 84 84 276
3 2001 Tom 99 88 76 263
4 2004 Mary 93 52 80 225
5 2005 Alice 62 89 74 225
```
相关推荐
![c](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)