首页 > 解决方案 > 在python上列出索引超出范围

问题描述

我试图用参数作为在函数内部处理的值来创建一些过程,但是有一些问题。这是我的一些代码

.
.
.
.
def pokerBruteForce(n:int, kombinasi:list, kartu:list, komposisi:list):
    c = 0
    i = 0
    j = 0
    k = 0
    l = 0
    m = 0
    done:bool
    teks:str
    if n <= 5:
        pass
    c = 0
    i = 0
    for i in range(n-1):
        done = False
        if ((n - c) > 4) and (kombinasi[i] == False):
            for j in range(i+1,(n - 1), 1):
                if kombinasi[j] == False and (((n - c) - 1) > 3):
                    if kartu[j].bobotCorak == kartu[i].bobotCorak and kartu[j].nilai == kartu[i].nilai - 1:
                        for k in range((i+1),(n - 1), 1):
                            if kombinasi[k] == False and (((n - c) - 2) > 2):
.
.
.
.

主要代码是

cards = []
combination = [False] * 5 
composition = []
createKartu(cards)
pokerBruteForce(7, combination, cards, composition)
for i in range(len(composition)):
    print(composition[i],) 

在尝试编译和运行程序时,出现错误,它说

Traceback (most recent call last):
  File "d:\xxx\xxx\xxxx\xxxx\xxxxx", line 330, in <module>
    pokerBruteForce(7, combination, cards, composition)
  File "d:\xxxx\xxxxx\xxxxxx\xxxx\xxxxx", line 54, in pokerBruteForce
    if kombinasi[j] == False and (((n - c) - 1) > 3):
IndexError: list index out of range

我正在尝试在 j 变量的循环中手动追溯代码,我认为我是对的。但它总是说它的错误。也许有什么解决办法?谢谢

标签: python

解决方案


你有kombinasi = [False]*5并且你尝试访问kombinasi[5]. 请记住,列表索引从 开始0,因此您只能访问kombinasi[4].

您应该j-1在以下行中使用:

for j in range(i+1,(n - 1), 1):
    if kombinasi[j-1] == False and (((n - c) - 1) > 3):

j或从ito迭代(n-2)

for j in range(i,(n - 2), 1):
    if kombinasi[j] == False and (((n - c) - 1) > 3):

推荐阅读