Python报错ValueErrorlist.remove(x)xnotinlist解决办法

博客 分享
0 213
优雅殿下
优雅殿下 2022-04-13 21:57:54
悬赏:0 积分 收藏

Python 报错 ValueError list.remove(x) x not in list 解决办法

平时开发 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、Django、Docker、Go、Redis、ElasticSearch、Kafka、Linux 等。
  • Go 程序员: Go 学习路线图,包括基础专栏,进阶专栏,源码阅读,实战开发,面试刷题,必读书单等一系列资源。
  • 面试题汇总: 包括 Python、Go、Redis、MySQL、Kafka、数据结构、算法、编程、网络等各种常考题。
posted @ 2022-04-13 21:55 yongxinz 阅读(0) 评论(0) 编辑 收藏 举报
回帖
    优雅殿下

    优雅殿下 (王者 段位)

    2018 积分 (2)粉丝 (47)源码

    小小码农,大大世界

     

    温馨提示

    亦奇源码

    最新会员