[英]"IndexError: list assignment index out of range" in python
i am trying to make battleship( in germany its called sink ships) And i have a problem, which is described in the title.我正在尝试制造战舰(在德国称为沉船)我有一个问题,在标题中有所描述。 There is nothing more to say, but i have to write something so i can post this.
没什么好说的,但我必须写点东西,这样我才能发布这个。 Can somebody pls help me, i do not see the problem
有人可以帮助我吗,我没有看到问题
from random import randint
class Spiel():
def __init__(self):
self.feld = [[],[],[],[],[],[],[],[],[],[]]
for i in range(0,10):
for e in range(0, 10):
self.feld[i].append(0)
def place(self):
boats = [5,4,4,3,3,3,2,2,2,2]
for e in boats:
while True:
ausrichtung = randint(0,1)
if ausrichtung==0: ##Horizontal
z1 = randint(0, 9-e)
z2=randint(0,9)
abschnitt = self.feld[z2][z1:(z1+e)]
if not(1 in abschnitt) and not(2 in abschnitt) :
schiff=[]
for i in range(0,e-2):
schiff.append(1)
self.feld[z2][z1:(z1+e)]=[2,*schiff,2]
break
elif ausrichtung==1: ##Vertikal
z1 = randint(0, 9)
z2=randint(0,(9-e))
z3 = z2
lp=0
for m in range(0, e):
if self.feld[z2][z1] ==1 or self.feld[z2][z1]==2:
lp +=1
z2 += 1
if lp <1:
schiff=[]
for i in range(0,e-2):
schiff.append(1)
self.feld[z3:(z3+e)][z1]=[2,*schiff,2] # PROBLEM HERE
break
print(self.feld[0:1])
print(self.feld[1:2])
print(self.feld[2:3])
print(self.feld[3:4])
print(self.feld[4:5])
print(self.feld[5:6])
print(self.feld[6:7])
print(self.feld[7:8])
print(self.feld[8:9])
print(self.feld[9:10])
spiel = Spiel()
spiel.place()
Error:错误:
Traceback (most recent call last):
File "test.py", line 56, in <module>
spiel.place()
File "test.py", line 40, in place
self.feld[z3 : (z3 + e)][z1] = [2, *schiff, 2]
IndexError: list assignment index out of range
Adding the following print statement before the line in which your code breaks reveals the following:在代码中断的行之前添加以下打印语句会显示以下内容:
print(len(self.feld), z3, (z3 + e), len(self.feld[z3 : (z3 + e)]), z1)
self.feld[z3 : (z3 + e)][z1] = [2, *schiff, 2]
10 1 6 5 1
10 2 5 3 8
Traceback (most recent call last): ...
It seems that z1
is 8
, yet self.feld[z3 : (z3 + e)]
has a length of 3
.似乎
z1
是8
,但self.feld[z3 : (z3 + e)]
的长度为3
。 Your issue is in the way the [z1]
is indexing.您的问题在于
[z1]
的索引方式。 Perhaps the following line:也许以下行:
z1 = randint(0, 9)
Is the culprit.是罪魁祸首。 :)
:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.