首页 > 解决方案 > 将具有“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

标签: pythonvalueerrortraceback

解决方案


OP,如果您要删除重复项,请使用:

list(set(list_of_names))

set(iterable)忽略重复项。


这是文档list.remove

s.remove(x) 从 s 中删除第一项,其中 s[i] 等于 x (3)

注脚注 (3)

  1. 当在 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 的原因。


推荐阅读