jx = 0
templist = [x for x in range(0,30)]
while True:
for x in range(1,6):
print(templist[jx])
print(x)
if len(templist) == jx:
break
else:
jx += 1
continue
jx = 0
templist = [x for x in range(0,30)]
break_outer = False
while True:
for x in range(1,6):
print(templist[jx])
print(x)
print len(templist)
if len(templist)-1 == jx:
break_outer = True
break
else:
jx += 1
if break_outer:
break
当
jx
达到len(templist)
(本例中为30)时,就会出现错误。您不能访问templist[30]
,因为索引是基于零的,因此最后一个是29。(比长度小1)您可以通过将
if
语句更改为if len(templist) == jx + 1:
来解决这个问题。或者将print
语句放在if/else子句之后。(如果您执行后一种操作,则需要删除continue
,但它在这里没有任何作用。)在尝试打印元素之后,您正在测试jx。反其道而行之。首先测试是否超出范围,然后打印元素并增加jx。你知道吗
jx继续不断增加,最终达到了一个不存在的圣殿骑士索引。圣殿骑士的长度是30。圣殿骑士团的最大值是29。因此,在比较templast的长度和jx的最大值时,需要进行-1比较。你还需要打破外部的while循环。你知道吗
相关问题 更多 >
编程相关推荐