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

简介: 平时开发 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]
复制代码


这样的话就没问题了。


以上就是本文的全部内容。


目录
相关文章
|
6天前
|
机器学习/深度学习 Shell 开发工具
Python使用管道执行git命令报错|4-7
Python使用管道执行git命令报错|4-7
|
6天前
|
Python
python常见报错
python常见报错
|
8天前
|
Linux 编译器 开发工具
快速在linux上配置python3.x的环境以及可能报错的解决方案(python其它版本可同样方式安装)
这篇文章介绍了在Linux系统上配置Python 3.x环境的步骤,包括安装系统依赖、下载和解压Python源码、编译安装、修改环境变量,以及常见安装错误的解决方案。
20 1
|
3天前
|
数据采集 Linux 网络安全
python 爬虫遇到的aiohttp证书错误解决办法
python 爬虫遇到的aiohttp证书错误解决办法
16 0
|
3天前
|
Python
Python量化炒股的获取数据函数— get_billboard_list()
Python量化炒股的获取数据函数— get_billboard_list()
|
6天前
|
缓存 Python
Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-npf9报错
Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-npf9报错
|
6天前
|
JSON 安全 数据格式
7-6|python报错TypeError: can't pickle _thread.RLock objects
7-6|python报错TypeError: can't pickle _thread.RLock objects
|
2月前
|
索引 Python
【Leetcode刷题Python】从列表list中创建一颗二叉树
本文介绍了如何使用Python递归函数从列表中创建二叉树,其中每个节点的左右子节点索引分别是当前节点索引的2倍加1和2倍加2。
38 7
|
2月前
|
SQL 机器学习/深度学习 算法
【python】python指南(五):静态类型注解之List
【python】python指南(五):静态类型注解之List
26 0
【python】python指南(五):静态类型注解之List
|
2月前
|
API 开发工具 Python
【Azure Developer】使用 Azure Python SDK时,遇见 The resource principal named https://management.azure.com was not found in the tenant China Azure问题的解决办法
【Azure Developer】使用 Azure Python SDK时,遇见 The resource principal named https://management.azure.com was not found in the tenant China Azure问题的解决办法
下一篇
无影云桌面