调用remove()等方法传入int型变量时报unknown variable x或ValueError
问题产生原因
- 核心错误是
counter变量仅在while循环外层计算了一次,进入循环后没有随列表元素的删除同步更新。以你代码中的name=1为例,初始统计得到counter=5,每执行一次list_of_names.remove(name)后,列表内1的数量已经减少,但counter的值仍为初始的5,导致循环会持续执行删除操作。等列表内的1被完全清空后,仍会调用remove(1),自然就抛出了x not in list的ValueError。 - 你提到的
unknown variable 'x'不属于运行时报错,是IDE的静态检测提示,和本次运行报错没有关联。
修复方案
最小改动修复
只需要把计数逻辑挪到while的循环条件中,每次循环都重新统计当前列表内对应元素的剩余数量即可:
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] for name in range(100): while list_of_names.count(name) > 1: list_of_names.remove(name) print(list_of_names)
更高效的去重方案
如果你只是要实现列表去重、保留元素首次出现的顺序,不需要自己写嵌套循环,Python 3.7及以上版本可以直接用字典的特性实现,性能远高于嵌套计数+删除的写法:
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] list_of_names = list(dict.fromkeys(list_of_names)) print(list_of_names)
如果不要求保留原有顺序,还可以更简单:
list_of_names = list(set(list_of_names))
内容的提问来源于stack exchange,提问作者flappybird
相关产品推荐
相关产品推荐

