Python 报错 ValueError list.remove(x) x not in list 解决办法
2022-04-13 21:55
597 查看
平时开发 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 UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 2: ordinal not in range(128)错误解决办法
- Android之error: void value not ignored as it ought to be(In function 'callMethod2')解决办法
- [解决办法]Python中使用json.loads解码字符串时出错:ValueError: Expecting property name: line 1 column 2 (char 1)
- Python中UnicodeDecodeError:‘XXX’ codec can’t decode bytes in position错误信息解决办法
- 安装VMware出现Error 1406:could not write value installpath to key的解决办法
- 小程序插件request:fail url “XXX” not in plugin’s domain list解决办法
- Jni使用过程中出现 error: request for member 'FindClass' in something not a structure or union,解决办法
- 编译内核时遇到“dpkg-gencontrol: error: package not in control info”的解决办法
- not an error (code 0): Could not open the database in read/write mode.的解决办法
- Python中ValueError: invalid literal for int() with base 10 的实用解决办法
- 运行Python2.x程序报编码错误的解决办法-UnicodeDecodeError: 'ascii' codec can't decode byte 0xb7 in position 7: ordina not in range(128)[0m
- Mysql5.7.25.1忘记root密码和修改用户密码报错ERROR 1054 (42S22): Unknown Column 'Password' In 'Field List'解决办法
- python2.7 使用super关键词 报错 TypeError: must be type, not classobj 解决办法
- Python中出现NameError: name 'display' is not defined的解决办法
- TypeError: Value passed to parameter 'input' has DataType float64 not in list of allowed values: fl
- 解决Python字符串处理出现错误UnicodeDecodeError: ‘ascii’ codec can’t decode byte 0xe4 in position 108: ordinal not in range(128)
- python2.7 使用super关键词 报错 TypeError: must be type, not classobj 解决办法
- TypeError: view must be a callable or a list/tuple in the case of include().解决办法
- MySQL 5.7 报错 ERROR 1054 (42S22): Unknown column 'password' in 'field list' 的解决办法
- Windows下pip安装及更新出现“UnicodeEncodeError: 'ascii' codec can't encode character u'\u258c' in position 8: ordinal not in range(128)”问题解决办法