[英]IndexError: string index out of range doesn't make sense
我有一個無法解釋的問題,我正在編寫一個程序來查找“最長的公共前綴”,但出現錯誤IndexError: string index out of range.
我注意到更改 if 語句的順序是解決方案,但這對我來說沒有意義。
這條線是:
if default[j] == list[i][j] and j < len(default):
問題的解決方法是:
if j < len(default) and default[j] == list[i][j]:
為什么會這樣,不是一樣的嗎? 我瞎了嗎?
這是有錯誤的代碼:
list=["hola", "holo", "holi"]
default=list[0]
for i in range(1, len(list)):
temp=""
if len(default)==0:
break;
for j in range(len(list[i])):
if default[j] == list[i][j] and j < len(default):
temp+=default[j]
else:
break
default=temp
print(default)
使用and
運算符時的順序很重要。
a and b
如果 a 為真,則僅檢查 b。 b 是否包含錯誤並不重要(語法錯誤除外)。
兩種說法並不相同。
如果我們有一個條件語句
if Condtion1 and Condetion2:
當且僅當 Condtion1 為真時,才會檢查 Conditon2。
讓我們檢查以下簡短示例,就會清楚:
a=10
b=0
if b!=0 and a/b>3:
print('Do Something')
else:
print('ok')
ok
就可以了
但是,如果我們對 if 語句中的條件重新排序, if a/b>3 and b:=0:
a=10
b=0
if a/b>3 and b!=0:
print('Do Something')
else:
print('ok')
后面的代碼給出錯誤ZeroDivisionError: division by zero
,其中,首先檢查 a/b 並且 b 等於 0。
但是,在第一個代碼中,條件 b,=0 首先被檢查,並給出False
,所以第二個條件a/b>3
沒有被處理。
所以,這兩個說法是不一樣的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.