2016-11-17 53 views
0

我還是新來的編程世界,有時我與最簡單的事情鬥爭......我寫了下面的代碼,它給了我一個ValueError: list.remove(x): x not in list當我想要超過它。我已經循環了原始列表的一個副本,這就是爲什麼我有點失落。這裏是代碼:正確使用remove()函數在Python +循環copyList

def revrot(strng, sz): 
    if len(strng) == 0 or sz <= 0 or sz > len(strng): 
     return '' 
    else: 
     list = [] 
     for i in strng: 
      list.append(i) 
     rest = len(strng)%sz 
     for i in range(0,rest): 
      list.pop() 
     sum = 0 
     res = '' 
     while len(list) != 0: 
      copyList = list[:] 
      for i in range(0,sz): 
       sum += 1 
       if sum%2 == 0: 
        list2 = list[:sz] 
        list2.reverse() 
        res += ''.join(list2) 
        print(res) 
        for i in range(0,sz): 
         list.remove(copyList[i]) 
       else: 
        res += ''.join(list[1:]) + ''.join(list[0]) 
        for i in range(0,sz): 
         list.remove(copyList[i]) 
    return res 

有趣的部分開始於while循環。我以爲我寫了一個函數,用於從list(範圍(0:sz)中刪除元素,因此在某些時候list是空的,這就是停止的時間。 我不明白的是:爲什麼我的remove()命令會拋出這ValueError異常它完美的控制檯時,我分別測試它?!

copyList 
Out[127]: ['1', '2', '3', '4', '5', '6', '7', '7', '9'] 

for i in range(0,4): 
    list.remove(copyList[i]) 

list 
Out[129]: ['5', '6', '7', '7', '9'] 

這就是爲什麼我很努力找出錯誤,因爲它工作在控制檯而不是在編輯器中感謝所有幫助

回答

0

你錯了,你正在刪除基於索引的項目,但是你忘記了當你刪除索引爲n的項目,您的商品n+1變成n

這裏您從列表開始刪除項目並繼續前進。列表中的項目也被反向交換。所以在這一點上,你會得到IndexError異常,因爲你現在所持有的物品的索引不在你實際預期的位置。它在遍歷列表中。

讓我們用一個例子看,這樣會更有意義,您:

>>> l = [1, 2, 3, 4, 5, 6, 7] 
>>> for i in range(len(l)): 
...  print 'index: ', i, 'list:', l 
...  del l[i] # better way to delete item in list based on index 
... 
index: 0 list: [1, 2, 3, 4, 5, 6, 7] 
index: 1 list: [2, 3, 4, 5, 6, 7] 
#    ^Item at zero index got deleted 
#     Now 2 is at index zero 

index: 2 list: [2, 4, 5, 6, 7] 
#    ^^ This time deleted item 3, because that is at index 2 

index: 3 list: [2, 4, 6, 7] 
index: 4 list: [2, 4, 6] 
Traceback (most recent call last): 
    File "<stdin>", line 3, in <module> 
IndexError: list assignment index out of range 

在最後它會引發指數的錯誤,因爲即使列表的初始長度爲7,當i4長度名單是3

+0

感謝您的回覆@MoinuddinQuadri。我以爲我通過在remove命令中使用copyList [i]擺脫了這個問題,因爲它不會查找範圍的索引,而是用於copyList [0] = 1等,因爲我正在循環copyList並沒有列出範圍是保持原來的,不是? –