python上的列表索引超出范围
我正试图制作一些程序,将参数作为函数内部处理的值,但存在一些问题。这是我的一些代码python上的列表索引超出范围,python,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
.
.
.
.
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):
.
.
.
.
它说,在试图编译和运行程序时,出现了一个错误
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
回溯(最近一次呼叫最后一次):
文件“d:\xxx\xxx\xxxx\xxxx\xxxx\xxxxx”,第330行,在
扑克暴力(7,组合,卡片,组合)
文件“d:\xxxx\xxxxx\xxxxxx\xxxxx\xxxxx\xxxxx”,第54行,在pokerBruteForce中
如果kombinasi[j]==False且((n-c)-1)>3:
索引器:列表索引超出范围
我试图在循环变量j中手动跟踪代码,我想我是对的。但它总是说它的错误。也许有什么解决办法?
谢谢您有
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
从i
迭代到(n-2)
:
为了消除明显的问题:
n
参数的值是否大于kombinasi
列表参数的大小?kombinasi
中的索引从0到4<范围(n-1)内的i的代码>从0到5。因此对于范围(i+1,(n-1),1)中的j:
可能超过4,这将导致列表索引超出范围。
for j in range(i+1,(n - 1), 1):
if kombinasi[j-1] == False and (((n - c) - 1) > 3):
for j in range(i,(n - 2), 1):
if kombinasi[j] == False and (((n - c) - 1) > 3):