本文目录导读:

我来帮你实现一个成绩排名脚本,包含多种常见场景和方法。
基础成绩排名脚本(Python)
# 基础成绩排名
scores = [85, 92, 78, 95, 88, 92, 76, 85]
# 简单排序(降序)
sorted_scores = sorted(scores, reverse=True)
print("成绩排名:", sorted_scores)
# 带排名的输出
def rank_scores(scores_list):
sorted_scores = sorted(scores_list, reverse=True)
for i, score in enumerate(sorted_scores, 1):
print(f"第{i}名: {score}分")
rank_scores(scores)
完整的学生成绩排名系统
class GradeRanking:
def __init__(self):
self.students = []
def add_student(self, name, scores_dict):
"""添加学生及成绩"""
total = sum(scores_dict.values())
student = {
'name': name,
'scores': scores_dict,
'total': total,
'average': total / len(scores_dict)
}
self.students.append(student)
def rank_by_total(self):
"""按总分排名"""
ranked = sorted(self.students, key=lambda x: x['total'], reverse=True)
self._display_rank(ranked, '总分')
def rank_by_subject(self, subject):
"""按单科成绩排名"""
ranked = sorted(self.students,
key=lambda x: x['scores'].get(subject, 0),
reverse=True)
self._display_rank(ranked, f'{subject}成绩')
def rank_with_ties(self):
"""带并列排名的处理"""
ranked = sorted(self.students, key=lambda x: x['total'], reverse=True)
print("\n=== 最终排名(含并列)===")
rank = 1
prev_score = None
for i, student in enumerate(ranked, 1):
if student['total'] != prev_score:
rank = i
print(f"第{rank}名: {student['name']} - 总分: {student['total']}")
prev_score = student['total']
def _display_rank(self, ranked_list, title):
print(f"\n=== {title}排名 ===")
for i, student in enumerate(ranked_list, 1):
print(f"第{i}名: {student['name']} - {title}: {student['total'] if 'total' in student else student['scores']}")
# 使用示例
if __name__ == "__main__":
ranking = GradeRanking()
# 添加学生
ranking.add_student("张三", {"语文": 85, "数学": 92, "英语": 88})
ranking.add_student("李四", {"语文": 78, "数学": 95, "英语": 82})
ranking.add_student("王五", {"语文": 92, "数学": 88, "英语": 90})
ranking.add_student("赵六", {"语文": 85, "数学": 85, "英语": 85})
# 各种排名方式
ranking.rank_by_total()
ranking.rank_by_subject("数学")
ranking.rank_with_ties()
Excel数据处理排名脚本
import pandas as pd
import numpy as np
def excel_grade_ranking(file_path, sheet_name=0):
"""处理Excel成绩表"""
try:
# 读取Excel文件
df = pd.read_excel(file_path, sheet_name=sheet_name)
# 计算总分
score_columns = df.select_dtypes(include=[np.number]).columns
df['总分'] = df[score_columns].sum(axis=1)
# 多种排名方式
df['排名'] = df['总分'].rank(ascending=False, method='min')
df['排名_dense'] = df['总分'].rank(ascending=False, method='dense')
df['排名_average'] = df['总分'].rank(ascending=False, method='average')
# 按排名排序
df_sorted = df.sort_values('总分', ascending=False)
# 保存结果
output_file = file_path.replace('.xlsx', '_排名.xlsx')
df_sorted.to_excel(output_file, index=False)
print(f"排名完成,结果保存至: {output_file}")
return df_sorted
except Exception as e:
print(f"错误: {e}")
return None
# 使用示例
# excel_grade_ranking('学生成绩表.xlsx')
Web服务器排名API
from flask import Flask, request, jsonify
from collections import defaultdict
import json
app = Flask(__name__)
class WebGradeRanking:
def __init__(self):
self.students = {}
def add_student(self, student_id, name, scores):
total = sum(scores.values())
self.students[student_id] = {
'name': name,
'scores': scores,
'total': total,
'average': total / len(scores)
}
def get_ranking(self, sort_by='total', page=1, per_page=10):
if sort_by == 'total':
ranked = sorted(self.students.values(),
key=lambda x: x['total'], reverse=True)
else:
ranked = sorted(self.students.values(),
key=lambda x: x['scores'].get(sort_by, 0),
reverse=True)
# 分页
start = (page - 1) * per_page
end = start + per_page
page_data = ranked[start:end]
return {
'total': len(ranked),
'page': page,
'per_page': per_page,
'data': [
{'rank': start + i + 1, **student}
for i, student in enumerate(page_data)
]
}
ranking_system = WebGradeRanking()
@app.route('/api/student', methods=['POST'])
def add_student():
data = request.json
ranking_system.add_student(
data['id'],
data['name'],
data['scores']
)
return jsonify({'message': '学生添加成功'})
@app.route('/api/ranking', methods=['GET'])
def get_ranking():
sort_by = request.args.get('sort_by', 'total')
page = int(request.args.get('page', 1))
per_page = int(request.args.get('per_page', 10))
result = ranking_system.get_ranking(sort_by, page, per_page)
return jsonify(result)
# 运行服务器
# app.run(debug=True)
命令行交互式排名脚本
#!/usr/bin/env python3
class InteractiveRanking:
def __init__(self):
self.students = {}
def run(self):
while True:
print("\n=== 成绩排名系统 ===")
print("1. 添加学生")
print("2. 查看排名")
print("3. 统计信息")
print("4. 清空数据")
print("5. 退出")
choice = input("请选择操作: ")
if choice == '1':
self._add_student()
elif choice == '2':
self._show_ranking()
elif choice == '3':
self._show_statistics()
elif choice == '4':
self.students.clear()
print("已清空所有数据")
elif choice == '5':
print("再见!")
break
else:
print("无效选择,请重试")
def _add_student(self):
name = input("学生姓名: ")
subjects = input("科目名称(用逗号分隔): ").split(',')
scores = {}
for subject in subjects:
score = float(input(f"{subject}成绩: "))
scores[subject.strip()] = score
total = sum(scores.values())
self.students[name] = {
'scores': scores,
'total': total,
'average': total / len(scores)
}
print(f"{name} 添加成功")
def _show_ranking(self):
if not self.students:
print("暂无数据")
return
ranked = sorted(self.students.items(),
key=lambda x: x[1]['total'],
reverse=True)
print("\n=== 成绩排名 ===")
print(f"{'名次':<4} {'姓名':<8} {'总分':<8} {'平均分':<8}")
print("-"*40)
for i, (name, data) in enumerate(ranked, 1):
print(f"{i:<4} {name:<8} {data['total']:<8} {data['average']:<8.1f}")
def _show_statistics(self):
if not self.students:
print("暂无数据")
return
totals = [s['total'] for s in self.students.values()]
averages = [s['average'] for s in self.students.values()]
print("\n=== 统计信息 ===")
print(f"学生人数: {len(self.students)}")
print(f"最高总分: {max(totals)}")
print(f"最低总分: {min(totals)}")
print(f"平均总分: {sum(totals)/len(totals):.1f}")
print(f"标准差: {self._std_dev(totals):.1f}")
def _std_dev(self, data):
mean = sum(data) / len(data)
variance = sum((x - mean) ** 2 for x in data) / len(data)
return variance ** 0.5
# 运行交互式系统
if __name__ == "__main__":
ranking = InteractiveRanking()
ranking.run()
简单shell脚本排名
#!/bin/bash
# 成绩排名shell脚本
scores_file="scores.txt"
# 创建示例数据
create_sample_data() {
cat > $scores_file << EOF
张三 85 92 78
李四 78 95 82
王五 92 88 90
赵六 85 85 85
EOF
echo "示例数据已创建"
}
# 计算总分并排名
rank_scores() {
if [ ! -f "$scores_file" ]; then
echo "成绩文件不存在"
return
fi
echo "成绩排名:"
echo "名次 姓名 语文 数学 英语 总分"
echo "----------------------------"
# 计算总分并排序
awk '{total=$2+$3+$4; print $1, $2, $3, $4, total}' $scores_file |
sort -k5,5nr |
awk 'BEGIN{rank=1} {printf "%d %s %s %s %s %d\n", rank, $1, $2, $3, $4, $5; rank++}'
}
# 主菜单
main() {
case "$1" in
init)
create_sample_data
;;
rank)
rank_scores
;;
*)
echo "使用方法: $0 {init|rank}"
;;
esac
}
main "$@"
使用建议
- 数据处理:使用Pandas处理大型Excel文件更高效
- Web应用:Flask适合构建简单的RESTful API
- 命令行:Python交互式脚本适合小型班级管理
- 并列排名:注意处理同分情况
- 性能优化:大量数据时考虑使用数据库
选择适合你需求的实现方式,可以根据具体场景进行扩展和优化。
版权声明:NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
足球直播
足球直播
足球直播
足球直播
足球直播
英超直播
英超直播
英超直播
英超直播
英超直播
篮球直播
篮球直播
篮球直播
篮球直播
篮球直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
中超直播
中超直播
中超直播
中超直播
中超直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
足球直播
足球直播
足球直播
足球直播
足球直播
英超直播
英超直播
英超直播
英超直播
英超直播
篮球直播
篮球直播
篮球直播
篮球直播
篮球直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
中超直播
中超直播
中超直播
中超直播
中超直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播