簡體   English   中英

當循環變量到達 for 循環中的范圍末尾時,此代碼如何不會出現索引錯誤?

[英]How does this code not get an index error when the loop variable gets to the end of the range in a for loop?

這是 edX 中的一個硬件問題,它要求我確定“bob”這個詞在某個字符串中出現了多少次。 我找到了一個解決方案,但我對它為什么起作用感到困惑。 對於代碼(1):

代碼(1)

s = 'azcbobobegghakl'
count = 0
for i in range(len(s)):
    if s[i:i+3] == "bob":
        count += 1
print(count)

在同一個硬件中,有一個問題要求我在某個字符串中按字母順序查找最長的子字符串。 在開始尋找解決方案時,我遇到了一個索引錯誤,因為我試圖引用一個超出范圍的索引; 此代碼中顯示:

代碼(2)

s = 'azcbobobegghakl'
temp = ''
longest = ''
for i in range(len(s)):
    if s[i] <= s[i+1]:
        temp += s[i+1]
        if len(temp) > len(longest):
            longest = temp
    else:
        temp = s[i+1]
print(longest)

錯誤(2)

Traceback (most recent call last):
  File "C:/Users/vchi/PycharmProjects/edX/introduction.py", line 5, in <module>
    if s[i] <= s[i+1]:
IndexError: string index out of range

為什么當 i > len(s)-4 和 s[i:i+3] 嘗試引用已排除的事物時,CODE(1) 不會遇到與 CODE(2) 收到的相同類型的錯誤界限? 先感謝您!

Python 切片在很多方面都很奇怪,這就是證明這一點的一種方式。

如果切片超出范圍,python 中的字符串只會將切片的“結束”設置為最后一個可行的索引,因此如果我們執行以下操作:

a = 'boboabcdef'

然后做了:

b = a[4:12]

我們只會得到 b 等於 'abcdef',因為它只會忽略字符串的其余部分。

但是當談到列表的索引時,python 有一個更嚴格的解釋,因為調試一個列表可能超出索引而沒有錯誤或警告的程序是非常困難的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM