平时开发 Python 代码过程中,经常会遇到这个报错:
ValueError: list.remove(x): x not in list错误提示信息也很明确,就是移除的元素不在列表之中。
比如:
>>> lst = [1, 2, 3]>>> lst.remove(4)Traceback (most recent call last): File "<stdin>", line 1, in <module>ValueError: list.remove(x): x not in list但还有一种情况也会引发这个错误,就是在循环中使用 remove 方法。
举一个例子:
>>> lst = [1, 2, 3]>>> for i in lst:... print(i, lst)... lst.remove(i)...1 [1, 2, 3]3 [2, 3]>>>>>> lst[2]输出结果和我们预期并不一致。
如果是双层循环呢?会更复杂一些。再来看一个例子:
>>> lst = [1, 2, 3]>>> for i in lst:... for a in lst:... print(i, a, lst)... lst.remove(i)...1 1 [1, 2, 3]1 3 [2, 3]Traceback (most recent call last): File "<stdin>", line 4, in <module>ValueError: list.remove(x): x not in list这样的话输出就更混乱了,而且还报错了。
那怎么解决呢?办法也很简单,就是在每次循环的时候使用列表的拷贝。
看一下修正之后的代码:
>>> lst = [1, 2, 3]>>> for i in lst[:]:... for i in lst[:]:... print(i, lst)... lst.remove(i)...1 [1, 2, 3]2 [2, 3]3 [3]这样的话就没问题了。
以上就是本文的全部内容,如果觉得还不错的话,环境点赞,转发和关注,感谢支持。
推荐阅读: