列表索引超出范围,但不显示在b中

2024-05-08 14:58:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我编写了一个简单的程序来检查字符串是否是彼此的子字符串。问题是我总是得到一个列表索引越界错误。在

我尝试在每次迭代中打印I和j,但它们从不超出列表的范围。我甚至尝试在s[5]和s[6]插入元素来检查索引,但仍然得到相同的错误。这个错误的原因是什么?在

s = []                                        
s.insert(0,str("a b c"))
s.insert(1,str("a b c d"))
s.insert(2,str("a b"))
s.insert(3,str("b c"))
s.insert(4,str("d"))

j = 0
i = 0

while j < 5:
    if s[j] in s[i]:
        print("\"" + s[j] + "\" is in the string \"" + s[i] + "\"")
    i +=1
    if i == 5 and j < 4:
        j+=1
        i=0

这是我的控制台输出

^{pr2}$

Tags: the字符串in程序元素列表ifis
3条回答

在代码引发异常时,i的值是5,而{}的值是4。在您的print语句中,您尝试执行s[i],即s[5],由于s的最大索引是4,所以您的代码正在提升IndexError。在

我相信,在您的代码中,您需要对if语句进行如下修改:

if i == 5 and j < 5:  # Instead of j < 4

那么您的代码运行良好:

^{pr2}$

似乎只有当i已经是5时才增加j(注意if子句中的and)。因此,当i=5时,您仍然处于while循环中(它只依赖于j),并且您尝试访问未定义的s[i]=s[5]。在

问题出在18号线

s = []                                        
s.insert(0,str("a b c"))
s.insert(1,str("a b c d"))
s.insert(2,str("a b"))
s.insert(3,str("b c"))
s.insert(4,str("d"))
print(s)
j = 0
i = 0

while j < 5:
    if s[j] in s[i]:

        print("\"" + s[j] + "\" is in the string \"" + s[i] + "\"")
    i +=1
    if i == 5 and j < 4: <-- here
        j+=1
        i=0

在某个时刻,您的i = 5j = 4,因此if i == 5 and j < 4语句的右侧为False,i不会重置为0。所以在下一个循环中,i等于5,最大索引是4。在

更好的解决方案是使用for循环。在

^{pr2}$

编辑以答复评论

^{3}$

相关问题 更多 >