本文目录导读:

我来为您提供一个统计红黄牌数量的Python程序,可以比较不同队伍的犯规情况。
基础版本
def count_cards(matches_data):
"""
统计各队红黄牌数量
matches_data: 字典,格式为 {'队名': {'红牌': 数量, '黄牌': 数量}}
"""
stats = {}
for team, cards in matches_data.items():
stats[team] = {
'红牌': cards.get('红牌', 0),
'黄牌': cards.get('黄牌', 0),
'总牌数': cards.get('红牌', 0) + cards.get('黄牌', 0)
}
return stats
def compare_teams(stats):
"""比较各队红黄牌总数"""
print("="*50)
print("各队犯规统计:")
print("-"*50)
# 按总牌数排序
sorted_teams = sorted(stats.items(), key=lambda x: x[1]['总牌数'], reverse=True)
for team, team_stats in sorted_teams:
print(f"{team}: 红牌{team_stats['红牌']}张, 黄牌{team_stats['黄牌']}张, 总牌数{team_stats['总牌数']}")
print("-"*50)
# 找出最多牌的球队
max_team = sorted_teams[0]
print(f"最多犯规: {max_team[0]},总牌数:{max_team[1]['总牌数']}张")
return sorted_teams
# 示例数据
match_data = {
'巴西': {'红牌': 2, '黄牌': 5},
'德国': {'红牌': 0, '黄牌': 3},
'阿根廷': {'红牌': 1, '黄牌': 4},
'法国': {'红牌': 3, '黄牌': 2}
}
# 执行统计
stats = count_cards(match_data)
compare_teams(stats)
进阶版本(包含更多功能)
import json
from datetime import datetime
class CardStatistics:
def __init__(self):
self.teams_data = {}
def add_match_data(self, team, red_cards=0, yellow_cards=0):
"""添加球队数据"""
if team not in self.teams_data:
self.teams_data[team] = {'红牌': 0, '黄牌': 0}
self.teams_data[team]['红牌'] += red_cards
self.teams_data[team]['黄牌'] += yellow_cards
def calculate_statistics(self):
"""计算统计数据"""
stats = {}
for team, cards in self.teams_data.items():
total = cards['红牌'] * 2 + cards['黄牌'] # 红牌权重更高
stats[team] = {
'红牌': cards['红牌'],
'黄牌': cards['黄牌'],
'总牌数': cards['红牌'] + cards['黄牌'],
'犯规指数': total
}
return stats
def display_report(self):
"""显示统计报告"""
stats = self.calculate_statistics()
print("\n" + "="*60)
print(f"红黄牌统计报告 - {datetime.now().strftime('%Y-%m-%d')}")
print("="*60)
# 按犯规指数排序
sorted_teams = sorted(stats.items(), key=lambda x: x[1]['犯规指数'], reverse=True)
# 打印表格头
print(f"{'球队':<10} {'红牌':<6} {'黄牌':<6} {'总计':<6} {'犯规指数':<8}")
print("-"*60)
for i, (team, s) in enumerate(sorted_teams, 1):
print(f"{i}. {team:<6} {s['红牌']:<6} {s['黄牌']:<6} {s['总牌数']:<6} {s['犯规指数']:<8}")
print("-"*60)
# 找出最多犯规的球队
max_team = sorted_teams[0]
min_team = sorted_teams[-1]
print(f"\n🏆 最纪律的球队: {min_team[0]}(仅{min_team[1]['总牌数']}张牌)")
print(f"⚠️ 最粗暴的球队: {max_team[0]}(共{max_team[1]['总牌数']}张牌)")
return sorted_teams
def save_to_file(self, filename="card_stats.json"):
"""保存数据到文件"""
with open(filename, 'w', encoding='utf-8') as f:
json.dump(self.teams_data, f, ensure_ascii=False, indent=2)
print(f"数据已保存到 {filename}")
# 使用示例
if __name__ == "__main__":
stats = CardStatistics()
# 添加多场比赛数据
stats.add_match_data("巴西", red_cards=2, yellow_cards=4)
stats.add_match_data("德国", red_cards=0, yellow_cards=2)
stats.add_match_data("阿根廷", red_cards=1, yellow_cards=3)
stats.add_match_data("法国", red_cards=3, yellow_cards=1)
stats.add_match_data("巴西", red_cards=1, yellow_cards=2) # 追加数据
stats.add_match_data("德国", red_cards=1, yellow_cards=1)
# 显示报告
stats.display_report()
图形化版本(使用 matplotlib)
import matplotlib.pyplot as plt
import numpy as np
def plot_card_statistics(teams_data):
"""绘制红黄牌柱状图"""
teams = list(teams_data.keys())
red_cards = [teams_data[t]['红牌'] for t in teams]
yellow_cards = [teams_data[t]['黄牌'] for t in teams]
x = np.arange(len(teams))
width = 0.35
fig, ax = plt.subplots(figsize=(10, 6))
bars1 = ax.bar(x - width/2, red_cards, width, label='红牌', color='red')
bars2 = ax.bar(x + width/2, yellow_cards, width, label='黄牌', color='yellow')
ax.set_ylabel('牌数')
ax.set_title('各队红黄牌统计')
ax.set_xticks(x)
ax.set_xticklabels(teams)
ax.legend()
# 在柱状图上显示数值
for bars in [bars1, bars2]:
for bar in bars:
height = bar.get_height()
ax.annotate(f'{int(height)}',
xy=(bar.get_x() + bar.get_width() / 2, height),
xytext=(0, 3),
textcoords="offset points",
ha='center', va='bottom')
ax.grid(True, axis='y', alpha=0.3)
plt.tight_layout()
plt.show()
# 使用示例
sample_data = {
'巴西': {'红牌': 3, '黄牌': 6},
'德国': {'红牌': 1, '黄牌': 3},
'阿根廷': {'红牌': 2, '黄牌': 4},
'法国': {'红牌': 4, '黄牌': 2}
}
plot_card_statistics(sample_data)
交互式版本
def interactive_card_counter():
"""交互式红黄牌统计程序"""
teams = {}
print("👋 欢迎使用红黄牌统计系统!")
while True:
print("\n" + "="*50)
print("1. 添加球队数据")
print("2. 查看统计报告")
print("3. 退出系统")
choice = input("请选择操作: ")
if choice == '1':
team_name = input("请输入球队名称: ")
try:
red = int(input("请输入红牌数量: "))
yellow = int(input("请输入黄牌数量: "))
if team_name not in teams:
teams[team_name] = {'红牌': 0, '黄牌': 0}
teams[team_name]['红牌'] += red
teams[team_name]['黄牌'] += yellow
print(f"✅ {team_name} 数据已保存")
except ValueError:
print("❌ 请输入有效的数字!")
elif choice == '2':
if not teams:
print("📊 暂无数据")
continue
# 计算统计
print("\n📊 统计报告:")
print("-"*50)
sorted_teams = sorted(teams.items(),
key=lambda x: x[1]['红牌']+x[1]['黄牌'],
reverse=True)
for i, (team, cards) in enumerate(sorted_teams, 1):
total = cards['红牌'] + cards['黄牌']
print(f"{i}. {team}: 红牌{cards['红牌']}张, 黄牌{cards['黄牌']}张, 总计{total}张")
# 找最多犯规的球队
max_team = sorted_teams[0]
print(f"\n⚠️ 犯规最多的球队: {max_team[0]},共{max_team[1]['红牌']+max_team[1]['黄牌']}张牌")
elif choice == '3':
print("👋 再见!感谢使用!")
break
else:
print("❌ 无效选择,请重试")
# 运行交互式程序
interactive_card_counter()
使用说明
这些程序各有特点:
- 基础版本:简单易懂,适合初学者
- 进阶版本:包含类封装、文件保存等功能
- 图形版本:可视化展示数据(需要安装matplotlib)
- 交互版本:用户可以直接输入数据
您可以根据需求选择合适的版本,如果需要更多定制功能,请告诉我具体要求!