我还是新来的编程世界,有时我与最简单的事情斗争......我写了下面的代码,它给了我一个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']
这就是为什么我很努力找出错误,因为它工作在控制台而不是在编辑器中感谢所有帮助
感谢您的回复@MoinuddinQuadri。我以为我通过在remove命令中使用copyList [i]摆脱了这个问题,因为它不会查找范围的索引,而是用于copyList [0] = 1等,因为我正在循环copyList并没有列出范围是保持原来的,不是? –