代码中的索引错误以随机显示图像而不重复

Index error in code to show image random without repetion

我试图随机显示一系列图像,但我想避免重复这些图像。

下面的代码在启动时有效,但有时会出现以下错误:

弹出索引超出范围

sufijos_png = list(range(1, 10+1))

def vars_for_template(self):
    n_img = random.choice(sufijos_png)
    self.player.n_loteria = n_img
    sufijos_png.pop(n_img-1)
    return dict(
        image_path='dict/G{}.png'.format(n_img)
    )´

Anyone have any idea how to fix this error?

.pop() 实际上 returns 和 删除了 列表的最后一个元素 sufijos_png,所以根据上面的逻辑,有可能在某些时候,它会尝试从列表 sufijos_png 中删除索引 n_img-1 处的元素,该元素不再存在。为了演示,让我们以您提供的示例为例:

sufijos_png = list(range(1, 10+1))
sufijos_png

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

注意 len(sufijos_png) = 10。现在,我们第一次从 sufijos_png 中随机选择一个值。假设值是 9,所以

n_img = random.choice(sufijos_png)
n_img
9

然后我们弹出(+ return)sufijos_pngn_img-1 = 9-1 = 8位置的值。

sufijos_png.pop(n_img-1) # pops value at index position 8
sufijos_png
[1, 2, 3, 4, 5, 6, 7, 8, 10]

现在,假设 sufijos_png 的下一次随机抽取等于 10(它是仍然保留在那里的值之一)。但是,sufijos_png 的长度现在是 9,所以索引范围是 0-8。因此以下将引发 IndexError:

n_img = random.choice(sufijos_png)
n_img
10 # one of the remaining possible values in sufijos_png

sufijos_png.pop(n_img-1) # pops value at index position 10, which doesn't exist

IndexError: pop index out of range

克服这个问题的一种方法,假设您只需要一个不重复的随机数来分配给 self.player.n_loteria = n_img,就是生成一个 digits/values 的列表,然后 shuffle 他们,然后继续从这个随机排序的列表中弹出。例如:

import random
sufijos_png = list(range(1, 10+1))
random.shuffle(sufijos_png) # just need to shuffle once

def vars_for_template(self):
    n_img = sufijos_png.pop() # every time you accessing, you're depleting the list
    self.player.n_loteria = n_img
    return dict(
        image_path='dict/G{}.png'.format(n_img)
    )