-1

我是 python 新手,正在 CS50 中做一个实验室 6 的问题,但遇到了错误:List index out of rang。尽管我已经复习了很多次,也看了课程的提示视频,但我仍然找不到解决这个问题的方法。请帮我。

这是我的代码:

# Simulate a sports tournament

import csv
import sys
import random

# Number of simluations to run
N = 1000


def main():

    # Ensure correct usage
    if len(sys.argv) != 2:
        sys.exit("Usage: python tournament.py FILENAME")

    teams = []
    # TODO: Read teams into memory from file
    with open(sys.argv[1], "r") as file:
        reader = csv.DictReader(file)
        # The line 22 is to skip the first line of the csv file
        next (reader)
        for row in reader:
            row["rating"] = int(row["rating"])
            teams.append(row)
    counts = {}
    # TODO: Simulate N tournaments and keep track of win counts
    for i in range(0,N,1):
        winner = simulate_tournament(teams)
        if winner in counts:
            counts[winner] += 1
        else:
            counts[winner] = 1
    # Print each team's chances of winning, according to simulation
    for team in sorted(counts, key=lambda team: counts[team], reverse=True):
        print(f"{team}: {counts[team] * 100 / N:.1f}% chance of winning")


def simulate_game(team1, team2):
    """Simulate a game. Return True if team1 wins, False otherwise."""
    rating1 = team1["rating"]
    rating2 = team2["rating"]
    probability = 1 / (1 + 10 ** ((rating2 - rating1) / 600))
    return random.random() < probability


def simulate_round(teams):
    """Simulate a round. Return a list of winning teams."""
    winners = []

    # Simulate games for all pairs of teams
    for i in range(0, len(teams), 2):
        if simulate_game(teams[i], teams[i + 1]):
            winners.append(teams[i])
        else:
            winners.append(teams[i + 1])

    return winners


def simulate_tournament(teams):
    """Simulate a tournament. Return name of winning team."""
    while len(teams) > 1:
        teams = simulate_round(teams)
    # "team" because the name "team" is define in the csv file. Because each element in teams list is a dictionary therefore
    # we need to add ["team"] meaning we will only return the name of the final winning team
    return teams[0]["team"]

if __name__ == "__main__":
    main()

运行时,出现此错误:

Traceback (most recent call last):
  File "/workspaces/86940196/world-cup/tournament.py", line 70, in <module>
    main()
  File "/workspaces/86940196/world-cup/tournament.py", line 29, in main
    winner = simulate_tournament(teams)
  File "/workspaces/86940196/world-cup/tournament.py", line 64, in simulate_tournament
    teams = simulate_round(teams)
  File "/workspaces/86940196/world-cup/tournament.py", line 53, in simulate_round
    if simulate_game(teams[i], teams[i + 1]):
IndexError: list index out of range

我确实尝试使用变量 i 在每个 for 循环之前添加 i = 0 ,但它也不起作用:(

4

1 回答 1

0

我只是意识到,当使用 csv.DictReader 时,该函数会自动将第一行视为“键”,因此无需添加 next(reader)。删除该行后,现在一切正常。

于 2022-01-23T11:23:31.927 回答