2015-06-24 52 views
1

我在Python,list1列表,下面的while循環:如何在Python中的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

如何解決這個問題?

+0

將'j = 0'改爲'j = 1'。 – Hamed

回答

10

你需要開始你的條件與長度檢查。 Python short-circuits在while循環中的操作,所以當j太大時,它只會拋出一個錯誤而不是優雅地結束循環。所以像這樣的:

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

你的循環的第一次迭代比較list1[0]list1[-1],這是有效,但可能不是你想要的東西在做(它的list1第一個和最後一個元素進行比較) 。根據您的目標,您可能希望或不希望通過j = 1開始循環。

1

當使用and時,如果第一個條件爲false,則不檢查第二個條件。簡單地使用:

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