首页 > 解决方案 > Python索引错误:列表索引超出范围

问题描述

我正在 Otree 上编写一个实验,让玩家输入他们的名字并参加谁捐出最多三分球的比赛。这些树是通过表单域输入的。轮数是一个预定义的变量。默认情况下,每个玩家在进入实验时都会获得一个 id(从 1 开始)我已经编写了整个代码,并且它可以与最多 5 名参与者一起工作,但现在我应该为最多 8 名参与者编写代码。当我尝试在 Otree 上输入参与者数量时,我收到错误消息“索引错误:列表索引超出范围”。

行中发生错误matrix[p.id_in_group - 1][0] = p.name matrix[p.id_in_group - 1][self.round_number] = p.cumulative_donated_trees

所以我猜矩阵的初始化是错误的?我只想有一个包含 2 列的矩阵:名称和树(当然还有索引列)和 n 行(n = 玩家数)```

模型.py:

class Donation(Page):
    try:
        form_model = 'player'
        form_fields = ['donation']

 def vars_for_template(self):
            names = []
            trees = []
            sortedtrees = []
            anzahlspalten = 0
            for p in self.subsession.get_players():
                if self.round_number == 1:
                    matrix[p.id_in_group - 1][0] = p.name
                matrix[p.id_in_group - 1][self.round_number] = p.cumulative_donated_trees
            for i in range(0, Constants.number_of_players):
                names.append(matrix[i][0])
                trees.append(matrix[i][self.round_number])
            sortedtrees = sorted(trees, reverse=True)
            anzahlspalten = len(sortedtrees)         
            for l in range(0, anzahlspalten):
                if self.player.cumulative_donated_trees == sortedtrees[l]:
                    self.player.current_position = str(l + 1)

模型.py:

name = models.StringField(label="Your first name:")
    transcribed_text = models.LongStringField()
    levenshtein_distance = models.IntegerField()
    guthaben = models.CurrencyField(initial=c(0))
    cumulative_guthaben = models.CurrencyField()
    cumulative_donation = models.FloatField(null=True)
    right_answer = models.BooleanField()
    right_answer_text = models.StringField()
    treatmentgroup = models.StringField()
    donation = models.FloatField(min=c(0))
    no_trees = models.FloatField(initial=0.0)
    cumulative_donated_trees = models.FloatField()
    current_position = models.StringField()
    spielstand = models.StringField()

回溯:

File "c:\users\wiwi-admin\appdata\local\programs\python\python37\lib\site-packages\otree\views\abstract.py" in get_context_data
  338.             user_vars = self.vars_for_template()

File "C:\Users\Wiwi-Admin\Desktop\Backup Version 2 - Competition WITHIN Treatmentgroups\Master thesis code\__pycache__\oTree\my_environmental_surveyTG4\pages.py" in vars_for_template
  252.                     matrix[p.id_in_group - 1][0] = p.name

Exception Type: IndexError at /p/tgv0j88z/my_environmental_surveyTG4/Donation/7/
Exception Value: list index out of range

标签: pythonmatrixindexingerror-handling

解决方案


推荐阅读