我寫了一個簡單的程序來檢查字符串是否是彼此的子字符串。問題是我不斷收到列表索引超出界限的錯誤。列表索引超出範圍,雖然看起來不是
我試着在每次迭代時打印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
這是我的控制檯輸出
Traceback (most recent call last):
"a b c" is in the string "a b c"
File "C:/Users/Kal/PycharmProjects/untitled/FSS2.py", line 16, in <module>
"a b c" is in the string "a b c d"
if s[j] in s[i]:
"a b c d" is in the string "a b c d"
IndexError: list index out of range
"a b" is in the string "a b c"
"a b" is in the string "a b c d"
"a b" is in the string "a b"
"b c" is in the string "a b c"
"b c" is in the string "a b c d"
"b c" is in the string "b c"
"d" is in the string "a b c d"
"d" is in the string "d"
Process finished with exit code 1
請注意,要添加在列表的末尾,您應該只是'.append'。 – jonrsharpe
'print(i,j)'在你循環的開始,它會很清楚。你應該檢查'如果我== 4和j <4:' –
@PadraicCunningham我嘗試使用該檢查,但我仍然得到相同的錯誤 – user6912880