平时开发 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]
这样的话就没问题了。
以上就是本文的全部内容。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有