簡體   English   中英

如何在Python的while循環中修復此錯誤?

[英]How to fix this error in while loop in Python?

我在Python中有一個列表, list1和以下while循環:

j = 0
while list1[j] >= list1[j - 1] and j < len(list1):
    # do something here and return k
    # k is always incremented
    j += k

我收到以下錯誤: IndexError: string index out of range

如何解決這個錯誤?

您需要通過長度檢查來啟動while條件。 Python會縮短 while循環中的操作,因此,當j太大時,它將拋出一個錯誤,而不是優雅地結束循環。 像這樣:

while j < len(list1) and list1[j] >= list1[j - 1]:

循環的第一個迭代是比較list1[0]list1[-1] ,這是有效的 ,但可能不是您想要做的(它比較list1的第一個和最后一個元素)。 根據您的目標,您可能希望也可能不希望以j = 1開始循環。

當使用and ,如果第一個條件為假,則甚至不檢查第二個條件。 只需使用:

j = 0
while j < len(list1) and list1[j] >= list1[j - 1]:
    # do something here and return k
    # k is always incremented
    j += k

暫無
暫無

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

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