平时开发 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]

这样的话就没问题了。
以上就是本次分享的全部内容,当初想要学习编程的小伙伴欢送关注Python技术大本营,获取更多技能与教程。