python - 将具有“int”“类型”的变量放入方法的参数即“.remove()”时获取“未知变量x”或“ValueError”
问题描述
为什么名称(变量)被解释器视为“未知变量'x'”而不被视为它具有的“值”。`
list_of_names = [1, 1, 1, 1, 1, 2, 2, 2, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3]
name = 0
for name in range(100):
counter = list_of_names.count(name)
while counter > 1:
list_of_names.remove(name)
print(list_of_names)
` 输出显示:
Traceback (most recent call last):
File "x", line 6, in <module>
list_of_names.remove(name)
ValueError: list.remove(x): x not in list
Process finished with exit code 1
解决方案
OP,如果您要删除重复项,请使用:
list(set(list_of_names))
set(iterable)
忽略重复项。
s.remove(x) 从 s 中删除第一项,其中 s[i] 等于 x (3)
注脚注 (3)
- 当在 s 中找不到 x 时,remove 会引发 ValueError。
这是正在发生的事情的一个例子:
s = [1, 2, 3]
s.remove(1)
print(s) # [2, 3]
s.remove(1) # ValueError because s does not have a 1
我不确定您要使用代码完成什么,但这就是您收到 ValueError 的原因。
推荐阅读
- python - 使用 python selenium 读取、写入和控制动态实例化的 HTML web 表
- angular - 当我路由到不同的组件时,我可以在 Angular 7 的后台调用 api 服务吗
- c# - WebClient 不报告 0Kb 文件
- postgresql - postgres 9.6 显示 default_tablespace
- sql - 如何通过 ssql 中的计算列计算下一个生日
- javascript - 使用 VSCode 保存文件时我只想运行 Prettier
- ios - 将资源 plist 文件复制到应用程序支持文件夹?
- swift - 无法在 tableview + uiimagepickerController 中更新头像
- javascript - 选择 2 标记被继承到下一行
- java - 更改所有配置文件中相同的文件?