def rmNegatives(L):
subscript = 0
for num in L: # here you run over a list which you mutate
if num < 0:
L = L[:subscript] + L[subscript:] # here you do not change the list (see comment above)
subscript += 1 # you have to do this only in the case, when you did not remove an element from the list
return L
一个正在运行的代码是:
def rmNegatives(L):
subscript = 0
for num in list(L):
if num < 0:
L = L[:subscript] + L[subscript+1:]
else:
subscript += 1
return L
代码注释:
不会更改您的列表。例如
^{pr2}$其他错误:
一个正在运行的代码是:
请参阅@aessette和@sshashank124的解决方案,以更好地实现您的问题。。。在
如果你愿意的话,你也可以用过滤器。在
为什么不使用列表理解:
示例
^{pr2}$对于您的版本,您在遍历列表的同时更改列表的元素。你应该绝对避免它,直到你确定你在做什么。在
当您声明这是一种使用
while
循环的练习时,以下内容也将起作用:相关问题 更多 >
编程相关推荐