【问题标题】:Exception Value: list assignment index out of range异常值:列表分配索引超出范围
【发布时间】:2014-11-30 23:38:17
【问题描述】:

下面的Django视图不断抛出错误

异常值:未定义全局名称“图像”

views.py

PATH_ONE_IMAGES = ['P1D1.jpg', 'P2D2.jpg', 'P3D3.jpg', 'P4D4.jpg', 'P5D5.jpg', 'P6D6.jpg', 'P7D7.jpg', 'P8D8.jpg', 'P9D9.jpg']


class SurveyWizardOne(SessionWizardView):                      
    def get_context_data(self, form, **kwargs):
        context = super(SurveyWizardOne, self).get_context_data(form, **kwargs)  
        if self.steps.current in ['5','6','7','8','9','10','11','12','13','14','15','16']:
            print '\nThe available list of Path_One images is', PATH_ONE_IMAGES

            images = []
            step = int(self.steps.current)

            if step in (5, 6, 7):
                images[step - 5] = image = random.choice(PATH_ONE_IMAGES)          
                PATH_ONE_IMAGES.remove(image)
                context['display_image'] = image

            elif step == 8:
                context['first_image'] = images[0]
                context['second_image'] = images[1]
                context['third_image'] = images[2]             

            elif step in (9, 10, 11):
                images[3 + step - 9] = image = random.choice(PATH_ONE_IMAGES)          
                PATH_ONE_IMAGES.remove(image)
                context['display_image'] = image

            elif step == 12:
                context['fourth_image'] = images[3]
                context['fifth_image'] = images[4]
                context['sixth_image'] = images[5]

            elif step in (13, 14, 15):
                images[6 + step - 13] = image = random.choice(PATH_ONE_IMAGES)          
                PATH_ONE_IMAGES.remove(image)
                context['display_image'] = image

            else:# self.steps.current == '16':
                context['fourth_image'] = images[6]
                context['fifth_image'] = images[7]
                context['sixth_image'] = images[8] 

            steps = ['5','6','7','9','10','11','13','14','15']              

            context.update({'steps': steps})

        return context 

当我用

定义“图像”时
        ....
        if self.steps.current in ['5','6','7','8','9','10','11','12','13','14','15','16']:

            images = []
            step = int(self.steps.current)

            if step in (5, 6, 7):
        ....

我明白了

异常值:列表赋值索引超出范围

如果我给它添加值

images = [0,1,2,3,4]

它们被硬编码并且不采用PATH_ONE_IMAGES的值

谁能看到我在这里做错了什么?如何定义图像数组,使其列表分配索引不会超出范围,因此可以更新?

【问题讨论】:

    标签: python django python-2.7


    【解决方案1】:

    您发布的代码可能缺少关键信息,但是,假设没有任何重要信息丢失,我认为罪魁祸首是您的代码(去除无用细节后)看起来像:

    images = []
    for x in something:
        images[index] = x
    

    无效有效。您不能使用常规分配将项目添加到列表中:

    In [1]: images = []
       ...: images[0] = 1
       ...: 
    ---------------------------------------------------------------------------
    IndexError                                Traceback (most recent call last)
    <ipython-input-1-d32b85fdcde7> in <module>()
          1 images = []
    ----> 2 images[0] = 1
          3 
    
    IndexError: list assignment index out of range
    

    当您使用name[index] = value 表示法时,您只能修改索引index 处的值,但这样的索引必须 已经存在于列表中,否则@987654325 @ 被提出。

    您必须使用append 在列表末尾添加,或使用insert 在特定索引中添加项目:

    In [2]: images = []
    
    In [3]: images.append(1)
    
    In [4]: images
    Out[4]: [1]
    
    In [5]: images.insert(0, 2)
    
    In [6]: images
    Out[6]: [2, 1]
    

    = 表示法只有在使用切片时才能改变列表的大小:

    In [7]: images[2:10] = range(8)
    
    In [8]: images
    Out[8]: [2, 1, 0, 1, 2, 3, 4, 5, 6, 7]
    

    事实上,通常使用切片的操作不会引发IndexError。即使images 是一个空列表,您也可以评估images[100:1000],它只会评估为一个空列表(因为索引超出范围,它会返回空列表),而images[100] 会引发IndexError)。

    【讨论】:

    • 嗨 Bakuriu。我添加了模式代码,以便您可以看到我想要实现的目标。
    • @Deepend 是的,从您现在发布的代码中可以清楚地看出问题是我在回答中所描述的。你有images = [],然后是for step in (5, 6, 7): images[step - 5] = something,这意味着循环尝试执行images[0] = something,正如我所说,这会引发错误,因为images 是空的。但是,我并没有真正得到您想要实现的目标。您的代码在某些时候尝试使用 images[8],但 images 在该代码中永远不会有 8 个元素。
    • 我在解释这一点时做得很糟糕。本质上,用户在每个页面上看到的是随机选择的不同图像。在三个这样的页面之后,用户应该再次看到前三个图像。 (数据验证页面)这种情况会发生 3 次,或 3 组,每组 3 次。
    • 我想填充一个列表,在这种情况下,images 将每个图像显示给用户,每个图像将进入特定位置。当他们在第 5 页(第一个图像页面)时,图像将保存到 images.insert(step - 5, image) 然后在第 8 步中,我可以选择图像 [0, 1, 2] 并将它们显示给用户。
    • 我最终在很多帮助下解决了这个问题,包括你的帮助。我以前从未听说过insert。谢谢
    【解决方案2】:

    使用append 函数将元素添加到列表中

    例如

    images=[]
    images.append(5)
    images.append(6)
    print images
    [5,6]
    

    因为您的 step5 开始意味着 images 列表从零开始,使用 append 语句正确插入

    所以代码应该是

    f step in (5, 6, 7):
                    images.append(random.choice(PATH_ONE_IMAGES))
                    PATH_ONE_IMAGES.remove(image)
                    context['display_image'] = image
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-05-31
      • 2020-09-17
      • 1970-01-01
      • 1970-01-01
      • 2020-02-03
      • 2011-03-16
      • 1970-01-01
      相关资源
      最近更新 更多