2015-10-18 81 views
3
def Task4(): 
    import random 
    t = True 
    list1 = [] 
    list2 = [] 
    rand = random.randint(1,6) 
    list1.append(rand) 
    print(list1) 
    for x in range(0,5): 
     if list1[0] == (rand): 
      list1.pop(0) 
     else: 
      list2.append(rand) 
      print(list2) 
      list1.pop(0) 

無法鍛鍊爲什麼if list1[0] == (rand):不斷提出列表索引超出範圍。列表索引超出範圍 - Python

+0

您需要檢查的第一個元素存在(即列表不爲空)索引之前 - >'如果列表1和列表1 [0] == rand' – grc

+0

調試你的代碼,你就會知道爲什麼。您可以使用鉛筆和紙張進行調試。 – Maroun

+0

您只在list1中追加了一個元素,但在循環中您試圖彈出5個元素。 – Andrew

回答

0
  • 當x爲0: - >你彈出現存唯一的列表項,因此列表爲空之後

  • 當x是1: - >您嘗試訪問列表1 [0] ,不存在 - >列表索引超出範圍的錯誤

+0

親愛的Downvoter,我對改進我的答案感興趣,因此:對於你低估了答案的答案有什麼不好?是的,它當然可以更完整,但鑑於這是一個簡單的問題,我認爲一個簡單的答案是可以的。 – DonCristobal

+1

我認爲你的答案是完美的。對downvote也好奇。無論如何,有我的讚賞。 –

3

讓我們看看會發生什麼list1

list1 = [] 

好的,該列表已創建,並且爲空。

rand = random.randint(1,6) 
list1.append(rand) 

rand被添加到列表中,所以在這一點list1 = [rand]

for x in range(0,5): 

這將循環四次;讓我們來看看第一次迭代:

if list1[0] == (rand): 

由於list1 = [rand]list1[0]rand。所以這個條件是真的。

list1.pop(0) 

索引0處的列表元素被刪除;由於list1只包含一個元素(rand),所以它現在再次變空。

for x in range(0,5): 

循環的第二次迭代,x1

if list1[0] == (rand): 

list1仍然是空的,所以在列表中沒有索引0。所以這個崩潰與一個例外。


在這一點上,我真的想告訴你如何解決以更好的方式了任務,但是沒有指定你正在嘗試做的,所以我只能給你一個提示:

當您從列表中刪除項目時,只能迭代列表中包含元素的頻繁項目。你可以使用while len(list1)循環(它將循環直到列表爲空),或者通過明確循環索引for i in len(list1)來完成。當然,您也可以避免從列表中刪除元素,並直接使用for x in list1直接循環項目。

0
truth is evident with debugging with print and try except: 

def Task4(): 
    import random 
    t = True 
    list1 = [] 
    list2 = [] 
    rand = random.randint(1,6) 
    list1.append(rand) 
    for x in range(0,5): 
     try: 
      print("list1 before if and pop",list1) 
      if list1[0] == (rand): 
       list1.pop(0) 
       print("list1 after pop",list1) 
      else: 
       list2.append(rand) 
       print("list2 {}".format(list2)) 
       list1.pop(0) 
     except IndexError as e: 
      print("Index Error {}".format(e)) 
      break 

Task4() 


list1 before if and pop [3] 
list1 after pop [] 
list1 before if and pop [] 
Index Error list index out of range