2015-02-10 99 views
2

我真的不明白爲什麼這個代碼存在一個列表項的檢查

a = [1,2,3,4,5,6,7,8,9] 

while a[0]: 
    a.remove(a[0]) 

print(a) 

不起作用。我收到的消息是「列表索引超出範圍」。但是,Python是否不檢查列表中是否有一個項目? 感謝

+1

你想做什麼?這看起來像一個XY問題。 – 2015-02-10 08:11:55

+0

如果你想循環播放列表並提取每一步的第一個元素,可以使用:'while a:first = a.pop()' – myaut 2015-02-10 08:14:19

回答

4

認爲,當你的列表是空的會發生什麼:

a = [] 

然後,你必須:

while a[0]: 

但..列表是空的,你會得到出界,例如:

a = [1,2,3] 

while a[0]: 
    a.remove(a[0]) 

    # first iteration: a = [2, 3] 
    # second iteration: a = [3] 
    # third iteration: a = [] 
    # fourth iteration: out of bounds since there's no a[0] 

解決方案:

更改while a[0]while a

1

當檢查最後的a[0]時,0索引本身超出範圍。可能是你想使用len(a)

a = [1,2,3,4,5,6,7,8,9] 

while len(a): 
    a.remove(a[0]) 

print(a) 

雖然它無法進行打印以外的任何其他[]

+2

或者簡單的'while a:' – Maroun 2015-02-10 08:45:40

+0

是:)絕對。 – 2015-02-10 08:53:37

1

當您運行的代碼是你告訴Python來不斷循環,會發生什麼而[0] (列表a的第一個元素)存在。每次循環運行時,都會從列表中刪除當前的第一個元素。當沒有更多的元素可以刪除python時拋出異常在你[0]條件的時候。 爲了避免這種情況,你可以做到以下幾點:

a = [1,2,3,4,5,6,7,8,9] 

try: 
    while a[0]: 
     print "removing the element:", a[0]   
     a.remove(a[0]) 
except IndexError: 
    print "no more elements to remove." 

這將順利地處理錯誤消息。

或者你可以有:

while len(a) > 0: 

這隻會只要你的列表中包含至少一個元素運行。

請注意,試圖打印您正在做的事通常可以幫助您調試代碼。

您可以閱讀這個discussion

相關問題