football.csv 记录了约 4万场足球比赛情况,截止2018年。 字段含义如下: date,home_team,away_team,home_score,away_score,tournament,city,country,neutral 日期/主队名称/客队名称/主队进球数(不含点球)/客队进球数(不含点球)/比赛类型/比赛所在城市/比赛所在国家/是否中立计算世界杯比赛中胜率最高的前5个队?将队伍名称及胜率保存在 top5 列表中。 约定: 胜率 = 获胜次数/总场次, 总场次为 (胜 + 平 + 负)计算胜率方法1: 循环+字典. 可考虑创建类似 dic={'国家1':[胜场次,总场次,胜率], '国家2':[胜场次,总场次,胜率] } 的字典。 # 方法1 dic = {} 计算胜率方法2: 用pandas完成
时间: 2024-02-21 19:57:55 浏览: 149
football_team_make
好的,根据您的要求,我将为您提供方法1的代码实现,计算世界杯比赛中胜率最高的前5个队,并将队伍名称及胜率保存在 top5 列表中。代码如下:
```python
import csv
# 创建字典存储每个国家的胜场次、总场次和胜率
dic = {}
# 读取football.csv文件
with open('football.csv', 'r') as file:
reader = csv.reader(file)
next(reader) # 跳过第一行表头
for row in reader:
# 判断比赛类型是否为世界杯比赛
if 'World Cup' in row[5]:
home_team = row[1]
away_team = row[2]
home_score = int(row[3])
away_score = int(row[4])
neutral = row[8]
# 判断比赛是否中立,如果是,则将主队和客队的进球数互换
if neutral == 'TRUE':
home_score, away_score = away_score, home_score
# 计算胜、平、负场次
if home_score > away_score:
winner = home_team
loser = away_team
result = 'win'
elif home_score == away_score:
winner = loser = ''
result = 'draw'
else:
winner = away_team
loser = home_team
result = 'lose'
# 更新字典中胜场次、总场次和胜率
for team in [home_team, away_team]:
if team not in dic:
dic[team] = [0, 0, 0]
dic[team][1] += 1
if result == 'win' and team == winner:
dic[team][0] += 1
dic[team][2] = dic[team][0] / dic[team][1]
# 按照胜率从大到小排序,取前5个队伍
top5 = sorted(dic.items(), key=lambda x: x[1][2], reverse=True)[:5]
# 输出结果
for i, (team, info) in enumerate(top5):
print(f'{i+1}. {team}: {info[0]}/{info[1]} ({info[2]:.2%})')
```
希望这个代码对您有所帮助!
阅读全文