Python嵌套For循环计算英超球队积分异常问题求助
问题:英超球队积分计算仅首个球队正确,后续无结果
我是Python新手,读取了包含2018/19赛季英超所有赛事数据的CSV文件,尝试用嵌套For循环逐个计算各球队赛季总积分,但只有首个球队(曼联)的积分计算正确,后续球队无法正常执行循环计算积分,相关代码如下:
import csv with open('EPL1819.csv') as file: eplgames = csv.DictReader(file) teampoints = list() eplteams = list() teamcount = 0 count = 0 # Outer loop going through teams one at a time for i in range(20): points = 0 # Inner loop going through each match for x in eplgames: # Populates the eplteams list if x['HomeTeam'] not in eplteams: eplteams.append(x['HomeTeam']) teamcount += 1 #print(eplteams[i]) # Works out the match result if x['FTHG'] > x['FTAG']: match_result = x['HomeTeam'] elif x['FTHG'] < x['FTAG']: match_result = x['AwayTeam'] else: match_result = "Draw" if eplteams[i] == match_result: points += 3 if eplteams[i] == x['HomeTeam']: if match_result == "Draw": points += 1 if eplteams[i] == x['AwayTeam']: if match_result == "Draw": points += 1 # Populates the teampoints list teampoints.append(points) print(eplteams[i]) print("Points:", points) print("Points List:", teampoints[i])
问题原因
核心问题有两个:
- 迭代器耗尽:
csv.DictReader返回的是一次性迭代器,第一次外层循环(计算第一个球队积分)时,内层循环已经把所有比赛数据遍历完了,后续外层循环再执行for x in eplgames时,迭代器已经没有数据了,所以内层循环直接跳过,积分保持0。 - 球队列表填充时机错误:在计算第一个球队积分的过程中才动态添加球队到
eplteams,这会导致后续循环中eplteams[i]的索引可能出现问题(比如前几个循环时球队列表还没填满20个)。
修复方案
- 先把所有比赛数据转换成列表,这样可以重复遍历多次;
- 提前收集所有球队,确保计算积分前
eplteams已经包含全部20支球队; - 优化积分计算逻辑,让代码更简洁清晰。
修复后的代码:
import csv with open('EPL1819.csv') as file: # 把迭代器转成列表,方便重复遍历 eplgames = list(csv.DictReader(file)) # 提前收集所有球队 eplteams = [] for game in eplgames: home_team = game['HomeTeam'] away_team = game['AwayTeam'] if home_team not in eplteams: eplteams.append(home_team) if away_team not in eplteams: eplteams.append(away_team) teampoints = [] # 遍历每支球队计算积分 for team in eplteams: points = 0 for game in eplgames: fthg = int(game['FTHG']) ftag = int(game['FTAG']) home_team = game['HomeTeam'] away_team = game['AwayTeam'] # 判断比赛结果 if fthg > ftag: winner = home_team draw = False elif fthg < ftag: winner = away_team draw = False else: draw = True # 计算积分 if not draw: if team == winner: points +=3 else: if team == home_team or team == away_team: points +=1 teampoints.append(points) print(f"{team}: {points} 分") # 可选:按积分排序输出完整积分榜 sorted_teams = sorted(zip(eplteams, teampoints), key=lambda x: x[1], reverse=True) print("\n赛季积分榜:") for idx, (team, pts) in enumerate(sorted_teams, 1): print(f"{idx}. {team} - {pts} 分")
内容的提问来源于stack exchange,提问作者Mr_salamander
相关产品推荐
相关产品推荐

