2016-11-17 30 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并没有列出范围是保持原来的,不是? –